4

Is it legal to return by value an object with a deleted copy constructor? For example, consider an object with an std::unique_ptr member. Most compilers do not complain when returning such objects by value because in most cases the compiler won't even look for the copy constructor. However, since (N)RVO is not required by the standard, is it okay to say that such programs are legal? Is std::move in the return statement necessary for standard compliance in these cases?

2

1 Answer 1

5

If you have a working move constructor, you may delete the copy constructor.

The following program works for me.

struct Foo
{
   Foo() = default;
   Foo(Foo const&) = delete;
   Foo(Foo&&) = default;
};

Foo test()
{
   Foo f;
   return f;
}

int main()
{
   Foo f = test();
   return 0;
}
5
  • Does this work without NRVO?
    – user3810155
    Sep 29, 2015 at 20:25
  • 2
    @xiver77 Yes, it does.
    – Baum mit Augen
    Sep 29, 2015 at 20:26
  • @xiver77 The compiler must reject any program that would not compile if copy elision were disabled
    – M.M
    Sep 29, 2015 at 20:41
  • I know this is an old question but could you explain why this is legal? Jul 15, 2019 at 19:39
  • 1
    @chessprogrammer, I haven't been able to isolate the specific paragraph/sentence in the standard that makes this legal. I suspect it's somewhere there in 12.8 Copying and moving class objects.
    – R Sahu
    Jul 17, 2019 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.