Re: Newbie sdt::move question 2 (not calling move constructor)
On 8/14/2014 1:51 PM, JiiPee wrote:
On 19/07/2014 14:46, Victor Bazarov wrote:
On 7/19/2014 7:24 AM, JiiPee wrote:
Why this code:
class X
{
public:
X();
X(const X& x);
X(X&& x);
};
X returnX()
{
X x;
return x;
}
int main()
{
X x;
X y(returnX());
}
does not call move constructor X(X&& x) when doing
X y(returnX());
?
This code only calls empty constructor X(); two times. returnX() returns
a temporary X object so it should go to move constructor automatically,
isnt it?
Read the FAQ (http://www.parashift.com/c++-faq-lite/). Pay special
attention to the section 10 'Constructors'. Can you find the relevant
question[s] and answer[s]?
V
No I cannot find it. Do you know the solution? If I send the temporary
object from returnX() to a function like:
void printReference (X&& str)
it goes there. Do why the contructor function is not taking it, the same
logic....
The constructor is optimized away. See FAQ 10.9.
The compiler is allowed to generate code so that the object y is
actually constructed where the local 'x' is 'returnX' is constructed.
Curiously, if you compile your code (with some visible side effect, like
a text output, in the move c-tor) as "Debug" in Visual C++, the side
effect is there, since by default the "Debug" configuration does not
optimize. If you then build it as "Release" (again, using default
settings), you won't see the output because the optimizer kicks in and
removes the extraneous call to the move c-tor, and no side effect is seen.
V
--
I do not respond to top-posted replies, please don't ask