移动unique_ptr< T>的向量 [英] Moving a vector of unique_ptr<T>

查看:154
本文介绍了移动unique_ptr< T>的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一种情况,我需要存储一个抽象类型的向量,因为我明白这需要使用一个unique_ptrs或类似的向量。

So I have a situation where I need to store a vector of an abstract type, as I understand this requires the usage of a vector of unique_ptrs or similar.

所以为了移动包含unique_ptrs向量的类的实例,我需要定义一个我已经做的移动构造函数。

So in order to move about instances of the class which contains the vector of unique_ptrs, I need to define a move constructor which I have done.

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

However as demonstrated by the example below, this seems to disagree with the compiler (msvc) which gives me the following error.


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

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 的东西,因为一个移动涉及源的突变。

You can't move from a const thing, because a move involves mutation of the source.

因此,正在尝试一个副本。

Therefore, a copy is being attempted instead. And, as you know, that's impossible here.

你的移动构造函数应该看起来像这样,没有 const

Your move constructor should look like this, with no const:

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

这篇关于移动unique_ptr&lt; T&gt;的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆