Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ copy constructor with shared_ptr members

From cplusplus.com:

Rarely you will come across a class that does not contain raw pointers yet the default copy constructor is not sufficient. An example of this is when you have a reference-counted object. boost::shared_ptr<> is example.

Can someone elaborate on this? If we have a class containing a boost::shared_ptr, won't that get copy constructed when the class gets copy constructed - and hence won't the shared_ptr constructor do the right thing and increase the reference count? The following code, for example, copies Inner properly - why wouldn't this work for shared_ptr?:

#include <iostream>
using namespace std;

class Inner
{
public:
 Inner() { cout << "inner default constructed" << endl;}
 Inner(const Inner& other) { cout << "inner properly copied" << endl;}
};

class Outer
{
 Inner i;
};

int main() { Outer o; Outer p(o); return 0;}
like image 289
Sideshow Bob Avatar asked Jul 24 '13 12:07

Sideshow Bob


2 Answers

Can someone elaborate on this?

Not really; it's gibberish.

If we have a class containing a boost::shared_ptr, won't that get copy constructed when the class gets copy constructed - and hence won't the shared_ptr constructor do the right thing and increase the reference count?

That's right. shared_ptr is properly designed with valid copy semantics, so there's no need to deal with it specially when copying a class object containing one.

Possibly, the author meant that if you want to copy, rather than share, the shared object, then you'll need a copy constructor to make a new one. However, it's rather strange to be using a shared_ptr if you don't want shared ownership.

like image 169
Mike Seymour Avatar answered Sep 21 '22 09:09

Mike Seymour


The default copy constructor will use the copy constructor for each member variable, or bit-wise copy for built-in types.

If you are using a shared pointer of some kind, the copy constructor will increment the shared count and both the original and the new objects will point to the same object.

In some cases, this is what you want; copying the pointer and correctly managing the reference count so that the resource can be freed when it is no longer used.

The context of the cited article is in copying an entire object. In this case, each object would be expected to have its own copy of its subobjects, and not share subobjects with other instances. In this case, shared_ptr is probably the wrong choice, and will definitely not deep-copy the subobjects.

The paragraph is badly phrased, but I'm sure it is talking about deep-copy but saying that shared_ptr will not provide that deep-copy. Which is true, because that isn't what it is designed for.

like image 22
cdmh Avatar answered Sep 22 '22 09:09

cdmh