Rule three with a smart pointer?

I'm a little confused using the "rule of three" with smart pointers. If I have a class whose single member is a smart pointer, do I need to explicitly define the destructor, copy constructor, and assignment operator?

I understand that since the smart pointer will process the resource automatically, then I do not need to explicitly define the destructor, and therefore I do not need to do this for the other two, based on the rule of three. However, I'm not sure if the default copy constructor is good enough for smart pointers like shared_ptr.

Thank you for your help!

+5
source share
3 answers

, shared_ptr . : , shared_ptr, . . , , , , , .

+10

, "". , "" , - .

:

class Foo
{
  std::shared_ptr<Bar> m_pbar;
  std::string          m_id;
};

, , , .

, , , , - , , , , .

+2

Rule three actually says:

If you need to define a non-trivial version of any of the following:

  • Destructor
  • Assignment operator
  • Copy constructor

... then you probably need the other two as well.

You seem to interpret it as:

If you need a nontrivial destructor, you also need two others.

But this is not exactly the same, is it?

+1
source

All Articles