Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a vector of unique_ptr<T> [duplicate]

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;
}
like image 875
Edward J Brown Avatar asked Feb 10 '23 13:02

Edward J Brown


1 Answers

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))
{}
like image 87
Lightness Races in Orbit Avatar answered Feb 13 '23 02:02

Lightness Races in Orbit