在尝试编写有关 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);
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.
和
std::move
obtains an rvalue reference to its argument and converts it to an xvalue.
我认为您描述的行为没有任何理由。也许您的编译器有问题?
编辑
看来,确实是编译器的问题。提案中描述了 move 函数的定义 N3053 (“定义 move 特殊成员函数”)。正如我们在 this page 上的表格中看到的那样:
关于c++ - 未调用 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747503/