我正在使用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;
}
emplace
:for (int i = 0; i < 5; ++i) s.emplace_back();
这也适用于 VC11。 - user2218982