小编zYz*_*zil的帖子

使用unique_ptr移动语义

我正在使用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); …
Run Code Online (Sandbox Code Playgroud)

c++ visual-c++ move-semantics c++11 visual-studio-2012

10
推荐指数
1
解决办法
9067
查看次数