Domanda

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

È stato utile?

Soluzione 2

No. It will sometimes lead to undefined behavior.

void f()
{
    string a{"a"};
    string b{"b"};
    auto&& c = move(a+b);
    ...
}

c will outlive the temporary produced by a+b. There are other ways to hit this issue also.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top