Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always use auto&& for local variable

Tags:

c++

c++11

auto

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&& ?

like image 915
Guillaume Paris Avatar asked Dec 25 '22 10:12

Guillaume Paris


1 Answers

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().

like image 101
nosid Avatar answered Jan 10 '23 15:01

nosid