[c++0x] cannot return a constant
Roman Kononov
roman@binarylife.net
Tue Nov 30 21:10:00 GMT 2010
2010-11-30 20:46 CST, Jonathan Wakely <jwakely.gcc@gmail.com> said:
>On 30 November 2010 20:40, Jonathan Wakely wrote:
>>> $ cat test1.cc
>>> struct X {
>>> Â X()=default;
>>> Â X(X&&)=default;
>>> Â X(X const&)=delete;
>>> Â //some very large or non-copyable content
>>> };
>>>
>>> X test() {
>>> Â X const x={};
>>> Â {
>>> Â Â //a lot of code where I do not want to modify x [accidentally]
>>> Â }
>>> Â return x;
>>> }
>
>To fix this broken code, either
>1) do not delete the copy constructor, you need it to return by value.
Cannot do it because of "//some very large or non-copyable content".
>or
>2) do not make 'x' const, and move from it with return std::move(x)
With x being non-const, move() is not required. And I really like using
"const" for a number of reasons. This is the crux of the question.
>>> $ cat test2.cc
>>> struct U {
>>> Â U();
>>> Â U(U&&);
>>> Â U(U const&);
>>> };
>>>
>>> struct X {
>>> Â U const u;
>>> Â X()=default;
>>> Â X(X&&)=default;
>>> Â //100 other members
>>> };
>>>
>>> X test() {
>>> Â X a={};
>>> Â return a;
>>> }
>
>To fix this broken code,
>1) do not define the X move constructor as defaulted, because the
>default definition attempts to move from U, which is const so the
>default definition is ill-formed
>and
Without the defaulted constructor I would have to type the code moving
all "//100 other members".
>2) define a copy constructor, explicitly-defaulted if you wish.
What if the copy constructor is too expensive and I have to use move
constructor?
Thanks
More information about the Gcc
mailing list