为什么有时不移动构造函数调用?测试移动语义(Live code):隐藏的移动建设
struct Test {
int id;
Test(int id) : id(id) {
cout << id << " Test() " << endl;
}
~Test() {
cout << id << " ~Test() " << endl;
}
Test(const Test &t) : id(t.id) {
cout << id << " Test(const Test &t) " << endl;
}
Test(Test &&t) : id(t.id) {
cout << id << " Test(Test &&t) " << endl;
}
Test &operator=(const Test &t) {
cout << id << " operator=(const Test &t) " << endl;
return *this;
}
Test &operator=(Test &&t) {
cout << id << " operator=(Test &&t) " << endl;
return *this;
}
};
void f(Test z) {
cout << z.id << " f(Test z) " << endl;
}
int main() {
f(Test(1));
Test t(2); f(t);
}
输出:
1 Test()
1 f(Test t) <---// where is move constructor ?!
1 ~Test()
2 Test()
2 Test(const Test &t) <---// copy constructor of t(2)
2 f(Test t)
2 ~Test()
2 ~Test()
试验表明拷贝构造函数被调用。
但是,经过f(Test(1));
功能f
被调用,而不必调用布展构造函数的Test(1)
右值对象。
它是一个隐式编译器优化?或者我错过了一个重要的观点?
第一步很可能被忽略了。 – goji
你正在得到一个副本elision。 – juanchopanza
我是唯一一个不明白的人吗?你的'f'采取'Test',而不是'Test &&',你为什么期望它会使用移动构造函数? – texasbruce