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?
Asked
Active
Viewed 1,078 times
4
-
You might consider this a duplicate: http://stackoverflow.com/questions/32844948/stdmove-and-rvo-optimizations – NathanOliver Sep 29 '15 at 20:17
-
And you do not need the move, the result of the function is an r-value anyways. – Baum mit Augen Sep 29 '15 at 20:27
1 Answers
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;
}

R Sahu
- 204,454
- 14
- 159
- 270
-
-
2
-
@xiver77 The compiler must reject any program that would not compile if copy elision were disabled – M.M Sep 29 '15 at 20:41
-
I know this is an old question but could you explain why this is legal? – chessprogrammer Jul 15 '19 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](https://timsong-cpp.github.io/cppwp/n4140/class.copy). – R Sahu Jul 17 '19 at 15:48