Move assignable class containing vector<unique_ptr<T>>

拈花ヽ惹草 提交于 2020-06-17 06:00:08

问题


The class Foo has an rvalue reference constructor that moves the contained vector of unique_ptrs so why does the following code give the following error, both with or without the std::move on the Foo() in main?

error C2280: 'std::unique_ptr<SomeThing,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
class Foo{
public:
    Foo(){

    }
    Foo(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;
    f = std::move(Foo());
    return 0;
}

回答1:


This:

 f = std::move(Foo());

doesn't call the move constructor. It calls the move assignment operator. Furthermore, it's redundant, since Foo() is already an rvalue so that's equivalent to:

f = Foo();

Since you declared a move constructor, the move assignment operator isn't declared - so there isn't one. So you either have to provide one:

Foo& operator=(Foo&& other) {
    m_bar = std::move(other.m_bar);
    return *this;
}

Or, since all your members implement move operations themselves, you could just delete your move constructor and rely on the compiler-generated implicit move constructor and move assignment.



来源:https://stackoverflow.com/questions/31430533/move-assignable-class-containing-vectorunique-ptrt

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