Should we always use auto && for a local variable

After reading this thread auto&&, does this mean that we should always use auto&&instead auto, when we declare a local variable to capture, the return type of the function (in order to accurately preserve the type returned by the function)?

Examples of use may be, for example,

auto&& result = func_returning_lvalue_or_lvalue_reference();

or

auto&& iterator = vector_.begin();

or something else.

In other terms, usually has a base code with a lot of auto&&?

+4
source share
2 answers

No. This sometimes leads to undefined behavior.

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

c will survive the time received by a + b. There are other ways to solve this problem.

+3

. auto&& . , , . auto&& ( ) .

:

auto&& name = customer.get_name(); // std::string or const std::string&
name.erase(name.find(' '));

? , ? , get_name().

+6

Source: https://habr.com/ru/post/1538175/


All Articles