Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler error when destructor declared in class body with unique_ptr as member of the same class

Below is the minimalist problem of the code:

struct B { 
  B () = default;
  //~B () {};  // error: use of deleted function ‘B& B::operator=(const B&)’
  std::unique_ptr<int> m_pB = nullptr;
};

int main ()
{
  std::vector<B> vB; 
  vB.erase(vB.begin());
}

Above code compiles fine, unless the destructor is uncommented. For my requirement, I need to have a body of ~B() explicitly defined.

How can I define the body of destructor with the unique_ptr co-existing in the same class?

Note: Tried defining = default versions of copy & move constructor to no avail. In my real code, unique_ptr<int> is unique_ptr<forward_declared_class>. Couldn't locate this problem in SO, though I am sure it must be present. Feel free to mark as dupe.

like image 907
iammilind Avatar asked Nov 17 '16 12:11

iammilind


Video Answer


1 Answers

Seems like your code requires B to be copy constructible and copy assignable for std::vector (at least for visual c++, which I tested).

Copy constructor and copy assignement operators can only be = delete because of std::unique_ptr (implementations declared = default should cause the function to be deleted as well), and, by implementing destructor, you disable default implementations of move constructor and move assignment operator.

So you need to explicitly declare the move assignment operator. Try:

#include <memory>
#include <vector>

struct B { 
  B () = default;
  ~B () {}
  B& operator=(B&&) = default;
  std::unique_ptr<int> m_pB = nullptr;
};

int main ()
{
  std::vector<B> vB; 
  vB.erase(vB.begin());
}
like image 124
rgmt Avatar answered Nov 15 '22 09:11

rgmt