加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 移动unique_ptr的向量

发布时间:2020-12-16 09:58:36 所属栏目:百科 来源:网络整理
导读:参见英文答案 Should a move constructor take a const or non-const rvalue reference?????????????????????????????????????4个 所以我有一种情况需要存储一个抽象类型的向量,据我所知这需要使用unique_ptrs或类似的向量. 因此,为了移动包含unique_ptrs向
参见英文答案 > Should a move constructor take a const or non-const rvalue reference?????????????????????????????????????4个
所以我有一种情况需要存储一个抽象类型的向量,据我所知这需要使用unique_ptrs或类似的向量.

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

但是,如下面的示例所示,这似乎不同意编译器(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事物中移动,因为移动涉及源的变异.

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读