Visual Studio 2012 Update 2 を使用していますが、std::vector が unique_ptr のコピー コンストラクターを使用しようとしている理由を理解するのに苦労しています。私は同様の問題を見てきましたが、ほとんどは明示的な移動コンストラクターおよび/または演算子がないことに関連しています。
メンバー変数を文字列に変更すると、移動コンストラクターが呼び出されたことを確認できます。ただし、unique_ptr を使用しようとすると、コンパイル エラーが発生します。
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
.
誰かが私が欠けているものを教えてくれることを願っています、ありがとう!
#include <vector>
#include <string>
#include <memory>
class MyObject
{
public:
MyObject() : ptr(std::unique_ptr<int>(new int))
{
}
MyObject(MyObject&& other) : ptr(std::move(other.ptr))
{
}
MyObject& operator=(MyObject&& other)
{
ptr = std::move(other.ptr);
return *this;
}
private:
std::unique_ptr<int> ptr;
};
int main(int argc, char* argv[])
{
std::vector<MyObject> s;
for (int i = 0; i < 5; ++i)
{
MyObject o;
s.push_back(o);
}
return 0;
}