ptr<T>>

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

Error 1 error C2280: 'std::unique_ptr> &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;
}

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.

链接地址: http://www.djcxy.com/p/59680.html

上一篇: std :: move需要返回std :: unique

下一篇: PTR <T >>