Search code examples
c++shared-ptrreference-countingnullptr

Semantic of empty shared_ptr


I've noticed a strange fact about shared_ptr

int* p = nullptr;
std::shared_ptr<int> s(p); // create a count (1).
std::shared_ptr<int> s2(s); // count go to 2.
assert(s.use_count() == 2);

I wonder what is the semantic beyond this. Why are s and s2 sharing a nullptr ? Does it makes any sense ?

Or maybe this uncommon situation doesn't deserve a if statement (costly ?) ?

Thanks for any enlightenment.


Solution

  • The semantics are:

    • If you default-construct a shared pointer, or construct one from nullptr_t, it's empty; that is, it doesn't own any pointer.
    • If you construct one from a raw pointer, it takes ownership of that pointer, whether or not it's null. I guess that's done for the reason you mention (avoiding a runtime check), but I can only speculate about that.

    So your example isn't empty; it owns a null pointer.