move-constructor が呼び出されないことがあるのはなぜですか? 移動セマンティクスのテスト(ライブ コード) :
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()
テストは、コピー コンストラクターが呼び出されることを示しています。
しかし、の右辺値オブジェクトに対して move-constructor を呼び出さずにf(Test(1));
関数が呼び出された後。f
Test(1)
それは暗黙のコンパイラ最適化ですか? または私は重要な点を逃しましたか?