Hacker News new | past | comments | ask | show | jobs | submit login
C++ Parameter Declaration Tutorial: Purpose of Different References (youtube.com)
10 points by ericdanielski on Sept 15, 2019 | hide | past | favorite | 1 comment



Nice video and cute examples. I have some disagreements though:

> "I find it to be a recommendable practice [when using an rvalue parameter] to always clear the object before returning, unless you already explicitly transferred the content ownership to another function or object before returning. This enforces the principle that whenever you use std::move, you can trust that the next time you access the object, it [is] in [a] blank state, as if it was just default-constructed."

This sounds like a potential source of bugs. The only guarantee given by the standard library is that moved-from objects are in a valid state, not a blank one. Making your private code uphold stronger invariants is only going to introduce confusion as to which functions do uphold it and which ones don't. Leave it to the code that std::moved to put the moved-from object into a specific state, if you need that.

> "You use rvalue references when you no longer need the contents of the object, and you want to move, or pass forward, it to a function."

This is a bit backwards, because it suggests that it's the needs of the caller that decide the parameter passing style. Rvalue reference arguments should only be used if the function receiving the parameter must move from the object. In practice, you should be writing this type of function very rarely, and clearly document the reason whenever writing one.

> "Pointers are like references, except more cumbersome and come with limitations. Pointers are what you must use in C if you need to modify the original value, but they are pretty much deprecated in C++, unless you have a very very good reason to use them."

That pointers would be deprecated in C++ just isn't true. Passing a raw pointer is the preferred style when "no object" is a valid value. Raw pointers have historically been used for lots of things in C++, and it's true that most of them are to be considered deprecated (e.g.: owning objects, pointing to C-style strings, passing arrays, etc.), but pointers as a whole are definitely not (and are unlikely to be in the future, even with std::optional).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: