Search code examples
c++c++11move

"error: use of deleted function" when calling std::move on unique_ptr in move constructor


#include <memory>

class A
{
public:
    A()
    {
    }

    A( const A&& rhs )
    {
        a = std::move( rhs.a );
    }

private:
    std::unique_ptr<int> a;
};

This code will not compile using g++ 4.8.4 and throws the following error:

error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>
::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_de
lete<int>]’
     a = std::move( rhs.a );
       ^

I understand that the copy constructor and copy assignment constructor for unique_ptr are deleted and cannot be called, however I thought by using std::move here I would be calling the move assignment constructor instead. The official documentation even shows this very type of assignment being done.

What is wrong in my code that I am not seeing?


Solution

  • A( const A&& rhs )
    // ^^^^^
    

    Drop the const -- moving from an object is destructive, so it's only fair that you can't move from a const object.