user1708860
user1708860

Reputation: 1753

Move constructor not called

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

Upvotes: 7

Views: 2147

Answers (2)

Mateusz Grzejek
Mateusz Grzejek

Reputation: 12058

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); or T a(std::move(b));, where b is of type T
  • function argument passing: f(std::move(a));, where a is of type T and f is void f(T t)
  • function return: return a; inside a function such as T 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:

enter image description here

Upvotes: 9

edmz
edmz

Reputation: 8494

Your code is well-formed and should call the move constructor. However, gcc 4.4, does not support defining move functions as stated here.

You do want to consider to update your compiler.

Upvotes: 3

Related Questions