c++11move-semanticsreturn-by-value

Copy ctor on return by value C++11


Is copy ctor needed for return-by-value in c++11 when there exists a move constructor? GCC 4.7.1 complains that the copy-ctor is implicity deleted since I only have a move constructor but I thought it should use the move constructor in this case.

VeryLargeObject foo(...)
    {
    VeryLargeObject ret;
    //Built object
    return ret; //<Error: VeryLargeObject has deleted copy-constructor
    }

I do not want to add the copy-constructor until I really need it.

EDIT:

Sorry I found that I forgot the move constructor... I only had move assignment :-(


Solution

  • No, you should only require a move constructor in this situation. Either your code has a bug (perhaps the move constructor was suppressed, or you didn't actually add it) or it's a GCC bug. It looks like based on your post edit, it was probably the former.

    A copy constructor would be needed if you tried to return an L-value other than a local variable. In that situation, you can turn an L-value into an R-value using move() to get it to work (realizing that you will then probably be changing the state of the L-value, of course).