1

I'm trying to understand what is wrong with following code where Result is a class with a move constructor:

Result&& GetResult(unsigned char* ptr)
{
    Result res = Result(ptr);
    return std::move(res);
}

Result ret = GetResult(ptr);

I know that the recommended way is to have return type Result and return res; and let compiler to call move constructor itself. But I want to understand what is going on in the case above with the lifetime of local variable res, because it seems to be "dead" at the time it is passed to move constructor in Result ret = GetResult(ptr);. On the other hand Result&& res = GetResult(ptr); keeps it alive.

iank
  • 336
  • 4
  • 8
  • 2
    rvalue references are still references, so this has all the problems that returning a `Result&` would have. Just return by value and move semantics will kick in. – François Andrieux Mar 21 '19 at 14:51
  • 2
    You can't a return a reference (of any kind) to local variable (or a temporary). It is undefined behavior. – SergeyA Mar 21 '19 at 14:51
  • 1
    The object `res` is destroyed right after the return statement is executed, *i.e.*, before the move constructor of `ret` starts running. – Brian Bi Mar 21 '19 at 14:55
  • 1
    If you return by value, in this case no move should happen at all, but ReturnValueOptimization (i.e., `res` is directly constructed at a place allocated by the calling function). – chtz Mar 21 '19 at 14:56
  • Don't return by `move` you prevent the compiler from potentially eliding the move. – Jesper Juhl Mar 21 '19 at 15:42

0 Answers0