【问题标题】:Moving a vector of unique_ptr<T> [duplicate]移动 unique_ptr<T> 的向量 [重复]
【发布时间】:2015-10-03 11:28:33
【问题描述】:

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

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

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

错误 1 ​​错误 C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_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;
}

【问题讨论】:

  • 摆脱const
  • Visual C++ 的哪个版本?因为VS2013之前不支持这个
  • 摆脱cmets中的答案。
  • @paulm 解决了这个问题,我习惯在引用参数之前使用 const,没有意识到它在移动构造函数中的重要性,你想把它作为答案发布吗?我会接受它。
  • 不妨接受轨道回答

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


【解决方案1】:

您不能从 const 事物中移动,因为移动涉及源的突变。

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

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

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

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 2014-07-21
    • 2016-06-21
    • 2014-10-12
    • 2017-09-24
    • 2018-02-02
    • 1970-01-01
    • 2016-05-11
    • 2019-07-14
    相关资源
    最近更新 更多