Moving a vector of unique_ptr<T> [duplicate]

梦想与她 提交于 2019-12-23 16:36:59

问题


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.

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.

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

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

回答1:


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.

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

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


来源:https://stackoverflow.com/questions/31413197/moving-a-vector-of-unique-ptrt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!