After reading this thread auto&&
, does it mean that we should always use auto&&
instead of auto
when we declare a local variable to capture the return type of a function (to exactly preserve the type returned by the function) ?
Use cases could be for instance
auto&& result = func_returning_lvalue_or_lvalue_reference();
or
auto&& iterator = vector_.begin();
or anything else.
In other terms it is normal to have a base code with a lot of auto&&
?
No. You should not use auto&&
all the time. In particular, you shouldn't use it, if you need a copy. With auto&&
you might get a copy (as a reference to a temporary object), or you might just get a reference to the original object.
For example:
auto&& name = customer.get_name(); // std::string or const std::string&
name.erase(name.find(' '));
Does this code compile? And if it compiles, does it change the name of the customer, or does it only work on a temporary object? You can't tell without looking at the signature of the function get_name()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With