c++ - 未调用 move 构造函数

标签 c++ c++11 move copy-constructor move-semantics

在尝试编写有关 move 构造函数的示例后,我遇到了以下代码:

#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;
}

为什么这里不调用 move 构造函数? 程序打印:

Data()

3

我发现更奇怪的是,通过添加复制构造函数,突然间,它确实调用了 move 构造函数...

    Data(const Data&)
    : x(2)
    {
        cout << "Data(copy)" << endl;
    }

现在它会打印

Data(&&)

4

P.S 我正在使用 gcc 4.4.5

最佳答案

好吧,你的代码对我来说工作正常。 See this sample .

输出:

Data()
Data(&&)
4

正如标准所说:

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.

std::move obtains an rvalue reference to its argument and converts it to an xvalue.

我认为您描述的行为没有任何理由。也许您的编译器有问题?


编辑

看来,确实是编译器的问题。提案中描述了 move 函数的定义 N3053 (“定义 move 特殊成员函数”)。正如我们在 this page 上的表格中看到的那样:

enter image description here

关于c++ - 未调用 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747503/

相关文章:

c++ - 尝试将右值传递给元组时错误使用已删除函数

javascript - aframe 相机在 VR 模式下不 move

c++ - 双符号返回类型是什么意思?

c++ - 在 iPhone 上将 utf-8 std::string 转换为 std::wstring

python - 如何在 NVIDIA Jetson TX2 上从 openCV(从源代码构建)运行 python?

c++ - unordered_map C++

c++ - 缺少分号 : C++ or SWIG issue?

c++ - 多次等待同一个锁

c++ - 在模板类的模板成员函数中设置优先于构造函数

c++ - 指针是否有可能在没有任何数据拷贝的情况下由 vector 拥有?