Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 883
user1708860 Avatar asked Apr 20 '15 12:04

user1708860


1 Answers

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

like image 103
Mateusz Grzejek Avatar answered Oct 12 '22 02:10

Mateusz Grzejek