c++11smart-pointersownership-semantics

What happens when a copy of a shared pointer is created whose object contains a unique pointer?


I have been messing about with SFML, figuring out how a simple 2D game could be built. I just noticed this behaviour and couldn't figure out what's going on. Sample code for what is confusing me:

struct Unique {};

class Shared {
public:
    Shared() {
        p = make_unique<Unique>();
    }
    unique_ptr<Unique> p;
};

void SharedCopyTest() {
    Shared foo;
    //Shared copy = foo;    // Error: function "Shared::Shared(const Shared &)" 
                            // (declared implicitly) cannot be referenced 
                            // -- it is a deleted function

    shared_ptr<Shared> sharedPtr = make_shared<Shared>();
    shared_ptr<Shared> ptrCopy = sharedPtr; // No error
}

At this point, &sharedPtr->p == &ptrCopy->p; but how is it possible, if p is of type unique_ptr<T>?


Solution

  • The semantics of std::shared_ptr is that no copies are made of the pointed-to object. Instead it's the std::shared_ptr object itself that is copied, and it increases the use-counter of the shared pointer.

    That why it works, because you're not actually making a copy of the Shared object.

    This can be easily verified by using the shared pointers get function to get the "raw" pointer:

    sharedPtr.get() == ptrCopy.get()