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.
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 documentationIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With