简体   繁体   English

移动未调用的构造函数

[英]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 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 4

PS I'm using gcc 4.4.5 PS我正在使用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 只要从相同类型的xvalue初始化对象,就会调用移动构造函数,其中包括

  • initialization, T a = std::move(b); 初始化, T a = std::move(b); or T a(std::move(b)); 或者T a(std::move(b)); , where b is of type T ,其中bT
  • function argument passing: f(std::move(a)); 函数参数传递: f(std::move(a)); , where a is of type T and f is void f(T t) ,其中a是T型, fvoid f(T t)
  • function return: return a; 功能返回: return a; inside a function such as T f() , where a is of type T which has a move constructor. 在诸如T f()之类的函数内部,其中a是T类型,它具有移动构造函数。

And

std::move obtains an rvalue reference to its argument and converts it to an xvalue . std::move获取对其参数的rvalue引用并将其转换为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"). 移动功能的定义在提案N3053 (“定义移动特殊成员功能”)中描述。 As we can see in table on this page : 正如我们在此页面上的表格中所示

在此输入图像描述

Your code is well-formed and should call the move constructor. 您的代码格式正确,应该调用移动构造函数。 However, gcc 4.4, does not support defining move functions as stated here . 但是,gcc 4.4不支持定义此处所述的移动函数。

You do want to consider to update your compiler. 您确实要考虑更新编译器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM