see the following code example:
#include <iostream> struct Foo { Foo() { std::cout << "Default!\n"; } Foo(const Foo& foo) { std::cout << "Copy!\n"; } Foo(Foo&& foo) { std::cout << "Move!\n"; } }; struct Bar { Foo foo; Bar() {} Bar(Bar &that) : foo(that.foo) {} Bar(Bar &&that) : foo(std::move(that.foo)) {} }; Bar f() { Bar bar; return bar; } int main() { Bar bar(f()); }
I expect the output of this code should be:
Default! Move!
but I get:
Default! Copy!
I see no reason why the copy constructor is called instead of the move constructor. If I put the const keyword before Bar &that in the declaration of the copy constructor struct Bar , I have the correct result. I know that in many cases it is better to take a reference to the lvalue constant, and not just the lvalue reference for copy constructors, but I just want to know the reason why this happened.
Why was Bar & preferable to Bar && in this example, although the return value of f() should be considered as prvalue? Why does the const keyword solve the problem? Does const really solve the problem? Is this related to RVO (Return Value Optimization)? Or is it just a compiler error?
I tested this example on Visual C ++ November 2012 CTP.
I found a similar problem:
Instead of the move constructor, the constructor instance is called
But I still canβt understand why.
Can anybody help me?
source share