このコードを別の質問に投稿しましたが、新たな疑問があります:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class X
{
public:
std::vector<double> data;
// Constructor1
X():
data(100000) // lots of data
{
cout << "X default constructor called";
}
// Constructor2
X(X const& other): // copy constructor
data(other.data) // duplicate all that data
{
cout << "X copy constructor called";
}
// Constructor3
X(X&& other): // move constructor
data(std::move(other.data)) // move the data: no copies
{
cout << "X move constructor called";
}
X& operator=(X const& other) // copy-assignment
{
cout << "X copy assignment called";
data=other.data; // copy all the data
return *this;
}
X& operator=(X && other) // move-assignment
{
cout << "X move assignment called";
data=std::move(other.data); // move the data: no copies
return *this;
}
};
class X2
{
public:
std::vector<double> data;
// Constructor1
X2():
data(100000) // lots of data
{}
// Constructor2
X2(X const& other): // copy constructor
data(other.data) // duplicate all that data
{}
X2& operator=(X const& other) // copy-assignment
{
data=other.data; // copy all the data
return *this;
}
};
X make_x()
{
X myNewObject; // Il normale costruttore viene chiamato qui
myNewObject.data.push_back(22);
return myNewObject; // Si crea un oggetto temporaneo prima di ritornare con il move constructor perchè myNewObject dev'essere distrutto
}
int main()
{
X x1 = make_x(); // x1 has a move constructor
X2 x2 = make_x(); // x2 hasn't a move constructor
}
main() 行では、move 割り当てと copy 割り当てが呼び出されることを期待しますが、そうではありません!
MSVC2012 の出力は次のとおりです。
X デフォルト コンストラクタと呼ばれる X ムーブ コンストラクタと呼ばれる X デフォルト コンストラクタと呼ばれる X ムーブ コンストラクタと呼ばれる
そしてg ++のものは
呼び出された X デフォルト コンストラクター 呼び出された X デフォルト コンストラクター
http://liveworkspace.org/code/220erd $2
課題はどこですか?? 最初の main() 行は移動代入を呼び出し、2 番目の main() 行はコピー代入を呼び出すと思いました