c++ - move unique_ptr<T> 的 vector

标签 c++ c++11 vector move-semantics unique-ptr

<分区>

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

因此,为了 move 包含 unique_ptr vector 的类的实例,我需要定义一个我已经完成的 move 构造函数。

然而,如下例所示,这似乎与编译器 (msvc) 不一致,编译器 (msvc) 给出了以下错误。

Error 1 error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function

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;
}

最佳答案

您不能从 const 对象 move ,因为 move 涉及源的变化。

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

你的 move 构造函数应该是这样的,没有const:

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

关于c++ - move unique_ptr<T> 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31413197/

相关文章:

C++ 2010 : using #include <mysql. h>

c++ - 使用 C++11 std::thread native_handle 以及我是否需要 CloseHandle

c++ - 初始化后的 vector at() 超出范围错误

c++ - std::vector<__m128i> 的内存布局

c++ - 如何在不显式定义函数的情况下创建函数的 std::vector?

c++ - 我们可以使用 lambda 表达式作为函数参数的默认值吗?

c++ - 在类内部处理回调时必须调用非静态成员函数的引用

c++ - 使用 std::function 的回调替代方案

matlab - 在 Matlab 中追加新数据的有效方法(附示例代码)

c++ - 类中成员函数声明的问题