Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor for class with shared_ptr data members?

I know how to write a copy constructor when you have raw pointer data members in a class, but how do you write a copy constructor when you manage these with a shared_ptr?

Is there a copy() or clone() function which should be called? Interestingly I have never seen such an example.

like image 559
user997112 Avatar asked Sep 08 '14 22:09

user997112


1 Answers

The copy constructor for std::shared_ptr creates a second pointer which shared ownership with the first pointer. The pointee will be destroyed when all std::shared_ptr that point to it are destroyed.

Without a copy constructor explicitly declared, the language specification decrees that a suitable one will be implicitly provided, and that it will call the copy constructors of each member of your class.

So, in other words, the implicit copy constructor provided for your class will call shared_ptr<T>::shared_ptr(const shared_ptr<T> &), which will create a second share pointer pointing to the same object, and it doesn't look like that's what you want. If you want a deep copy of the pointee, you will have to declare your own copy constructor that creates one:

class Foo
{
    Foo(const Foo &other)
      : foobar(new Bar(*other.foobar.get()))
    {}

    shared_ptr<Bar> foobar;
}

References:

  • std::shared_ptr constructor documentation
  • Copy constructor semantics in C++98 (see section 12.8.8) and C++11 (see section 12.8.16)
like image 181
Wug Avatar answered Sep 23 '22 14:09

Wug