移动unique_ptr <T>的向量

Edw*_*own 3 c++ vector unique-ptr move-semantics c++11

所以我有一种情况需要存储一个抽象类型的向量,据我所知这需要使用unique_ptrs或类似的向量.

因此,为了移动包含unique_ptrs向量的类的实例,我需要定义一个我已经完成的移动构造函数.

但是,如下面的示例所示,这似乎不同意编译器(msvc),它给出了以下错误.

错误1错误C2280:'std :: unique_ptr> :: unique_ptr(const std :: unique_ptr <_Ty,std :: default_delete <_Ty >>&)':尝试引用已删除的函数

class SomeThing{

};

class Foo{
public:
    Foo(){

    }
    Foo(const Foo&& other) :
        m_bar(std::move(other.m_bar))
    {};

    std::vector<std::unique_ptr<SomeThing>> m_bar;
};

int main(int argc, char* argv[])
{
    Foo f;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 7

你无法摆脱任何const事情,因为移动涉及源的变异.

因此,正在尝试复制.而且,如你所知,这在这里是不可能的.

你的移动构造函数应该如下所示,没有const:

Foo(Foo&& other)
    : m_bar(std::move(other.m_bar))
{}
Run Code Online (Sandbox Code Playgroud)