In which cases "std :: move" should be used in "return" operations and in which it should not

There are many similar questions. All of them asked about the use std::movein returnspecific cases. But I want to know when std::moveshould (or should not) be used in the expression returnas a whole.

Here I found the following answer:

All returned values ​​are already moved or optimized, so there is no need to explicitly move with the returned values.

Compilers are allowed to automatically move the return value (to optimize the copy) and even optimize the move!

Therefore, I expected that it std::moveshould never be used in a return statement, because in any case, the compiler optimizes this. But I decided to check this out and wrote the following test code:

class A
{
public:
    A() {}
    A(const A  & a) { std::cout << "A(const A  &)" << std::endl; }
    A(      A && a) { std::cout << "A(      A &&)" << std::endl; }
};

A func1(bool first)
{
    A a1, a2;
    return (first ? a1 : a2);
}

int main()
{
    A a1(func1(true));
    return 0;
}

And here is what I got:

A(const A  &)

Therefore, the compiler did not automatically move the value to the return statement, and I had to manually move it:

    return std::move(first ? a1 : a2);

This returns:

A(      A &&)

However, when I rewrote my code this way:

A func2(bool first)
{
    A a1, a2;
    if (first) return a1; else return a2;
}

int main()
{
      A a2(func2(true));
      return 0;
}

I found that automatic progress works:

A(      A &&)

Next test:

A func3(A &&a)
{
    return a;
}

int main()
{
    A a3(func3(A()));
    return 0;
}

Result:

A(const A  &)

So here you have to use return std::move(a).

. ( RVO) ( ( )). Rvalue (, , , - ). , "" return (return var;) , (return <some expression using var>, return somefunc(var);).

, std::move "return local variable" ( std::move ). std::move return.

?

+4

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


All Articles