Why is the size of make_shared two pointers?

Viewed 16268

As illustrated in the code here, the size of the object returned from make_shared is two pointers.

However, why doesn't make_shared work like the following (assume T is the type we're making a shared pointer to):

The result of make_shared is one pointer in size, which points to of allocated memory of size sizeof(int) + sizeof(T), where the int is a reference count, and this gets incremented and decremented on construction/destruction of the pointers.

unique_ptrs are only the size of one pointer, so I'm not sure why shared pointer needs two. As far as I can tell, all it needs a reference count, which with make_shared, can be placed with the object itself.

Also, is there any implementation that is implemented the way I suggest (without having to muck around with intrusive_ptrs for particular objects)? If not, what is the reason why the implementation I suggest is avoided?

4 Answers
Related