Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

move

#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?

like image 571
Fat-chunk Avatar asked Mar 06 '17 09:03

Fat-chunk


1 Answers

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.

like image 180
Quentin Avatar answered Sep 21 '22 23:09

Quentin