我正在研究C++11,我不明白为什么在下面的代码中
class X
{
std::vector<double> data;
public:
// Constructor1
X():
data(100000) // lots of data
{}
// Constructor2
X(X const& other): // copy constructor
data(other.data) // duplicate all that data
{}
// Constructor3
X(X&& other): // move constructor
data(std::move(other.data)) // move the data: no copies
{}
X& operator=(X const& other) // copy-assignment
{
data=other.data; // copy all the data
return *this;
}
X& operator=(X && other) // move-assignment
{
data=std::move(other.data); // move the data: no copies
return *this;
}
};
X make_x() // build an X with some data
{
X myNewObject; // Constructor1 gets called here
// fill data..
return myNewObject; // Constructor3 gets called here
}
int main()
{
X x1;
X x2(x1); // copy
X x3(std::move(x1)); // move: x1 no longer has any data
x1=make_x(); // return value is an rvalue, so move rather than copy
}在队伍中
return myNewObject; // Constructor3 gets called here调用Constructor3。为什么?
发布于 2013-03-30 20:31:38
X make_x() // build an X with some data
{
X myNewObject; // Constructor1 gets called here
// fill data..
return myNewObject; // Constructor3 gets called here
}myNewObject会在这个函数作用域的末尾被销毁,所以编译器只要动一动就可以把它的内脏挖出来。
发布于 2013-03-30 21:18:54
你会看到一个移动结构,因为你的编译器并没有做标准所允许的所有优化。
名义上,变量myNewObject被移动构造为make_x的返回值temporary,然后将临时变量移动赋值给x1。这就是你所看到的。
然而,在这种情况下,标准允许“移动构造函数省略”。它基本上和“复制构造函数省略”是一样的,在C++03中你可能对此很熟悉。这意味着编译器可以将变量myNewObject和make_x的返回值temporary转换为单个对象。这样就只剩下移动赋值了。
显然,你的编译器没有做移动省略。
如果你期望一个拷贝,那么它是一个移动的原因是,在C++11中,一个符合复制省略条件的返回值(这个是)被显式地要求被移动,而不是在移动可用的地方被复制。我记不住参考资料,手头也没有标准,所以你只能相信我的话。
https://stackoverflow.com/questions/15718498
复制相似问题