After trying to write an example regarding move constructors, I ran into the following code:
#include <utility>
#include <iostream>
using namespace std;
class Data
{
public:
Data()
: x (3)
{
cout << "Data()" << endl;
}
Data(Data&&)
: x(4)
{
cout << "Data(&&)" << endl;
}
int x;
};
int main()
{
Data a;
Data b (std::move(a));
cout << b.x << endl;
return 0;
}
Why is the move constructor not called here? The program prints:
Data()
3
What I'm finding even weirder is that by adding a copy constructor, suddenly, it does call the move constructor...
Data(const Data&)
: x(2)
{
cout << "Data(copy)" << endl;
}
And now it will print
Data(&&)
4
P.S I'm using gcc 4.4.5
Well, your code works properly for me. See this sample.
Output:
Data()
Data(&&)
4
As standard says:
The move constructor is called whenever an object is initialized from xvalue of the same type, which includes
- initialization,
T a = std::move(b);
orT a(std::move(b));
, whereb
is of typeT
- function argument passing:
f(std::move(a));
, where a is of typeT
andf
isvoid f(T t)
- function return:
return a;
inside a function such asT f()
, where a is of type T which has a move constructor.
And
std::move
obtains an rvalue reference to its argument and converts it to an xvalue.
I see no reason for behavior you describe. Perhaps there is something wrong with your compiler?
EDIT
It seems, that it is indeed the fault of the compiler. Definition of move functions was described in proposal N3053 ("Defining Move Special Member Functions"). As we can see in table on this page:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With