Question

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.

Was it helpful?

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.

OTHER TIPS

Who cares that they are sharing the nullptr? As soon as they are both destroyed, they will attempt to delete nullptr; which will have no effect. That's perfectly okay and fits in with the semantics of shared_ptr.

It makes sense in the way that no special case is required for null pointer values. Whether it occurs in your code just comes down to whether you have some function that can take or return null shared_ptrs.

shared_ptr will count and free whatever pointer it was given(not only nullptr, but something invalid as well). so in your example this will end up with nullptr being deleted which is valid case. Is it still safe to delete nullptr in c++0x?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top