# V828. Decreased performance. Moving an object in a return statement prevents copy elision.

The analyzer has detected an issue where a local variable, a function parameter or a temporary object is returned from a function by calling 'std::move'.

Consider the following contrived example:

    struct T { .... };

    T foo()
    {
      T t;
      // ....
      return std::move(t);
    }

This code may seem better optimized as the move constructor is guaranteed to be called first, but this is really a misconception. The use of 'std::move' in the context of the return expression will prevent the analyzer from deleting the call to the copy / move constructor (copy elision, C++17) and applying the RVO/NRVO to local objects.

Before the move semantics was introduced (in C++11), compilers would try to do the so called [Named] Return Value Optimization (RVO/NRVO) without calling the copy constructor so that the return object was created directly on the stack of the caller function and then initialized by the callee function.

The compiler can do this optimization only if the return type of the function is a non-reference while the operand of the 'return' statement is the name of a local non-'volatile' variable and its type is the same as the return type of the function (ignoring the 'const' / 'volatile' qualifier).

Starting with C++11, when returning a local non-'volatile' variable, the compiler will try to apply the RVO/NRVO, then the move constructor, and only then the copy constructor. Therefore, the following code is slower than expected:

    struct T { .... };

    T foo()
    {
      T t;
      // ....
      return std::move(t); // <= V828, pessimization
    }

In the case of a non-'volatile' formal parameter, the compiler cannot apply the RVO/NRVO due to technical reasons, but it will try to call the move constructor first and then the copy constructor. Therefore, the following code contains a redundant 'std::move' function call, which can be omitted:

    struct T { .... };

    T foo(T param)
    {
      T t;
      // ....
      return std::move(param); // <= V828, redundant 'std::move' call
    }

Also, starting with C++17, if the return expression is a prvalue (for example, the result of calling a function that returns a non-reference value), the compiler must optimize the code by deleting the call to the copy / move constructor (copy elision). Therefore, the following code is slower than expected:

    struct T { .... };

    T bar();

    T foo()
    {
      return std::move(bar()); // <= V828, pessimization
    }

In all cases presented, it's recommended to remove the 'std::move' function call in order to optimize the code, or to omit the redundant one.References:

- C++20 (working draft N4860), 11.10.5
- C++ Core Guidelines F.48: Do not return std::move(local)