c++ copy constructor with shared_ptr members

c++, copy-constructor, shared-ptr

Solution

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.

Problem

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;} ```

Original source