I am missing something about shared/weak pointers:
When a shared_ptr
is constructed using make_shared
, only one memory allocation is used (to allocate memory for control block and object itself). What happens when last shared_ptr
is destroyed but there are weak_ptr
-s left? At this point managed object has to be deallocated. But if memory allocated by make_shared
gets deallocated, that would make weak pointers invalid, since same deallocation would destroy control block.
With
make_shared
andallocate_shared
, there's only one single reference control block that contains the object itself. It looks something like this:The object is constucted in-place:
::new (internal_memory.buf) T(args...)
.Memory for the entire block is allocated with
::operator new
, or in case ofallocate_shared
with the allocator'sallocate()
function.When the object is no longer needed, the destructor is called on the object itself, some thing like
internal_memory.buf->~T();
. When the reference control block is no longer needed, i.e. when all the weak references have disappeared as well as all the strong ones, the reference control block as a whole is freed with::operator delete
, or with the allocator'sdeallocate()
function forallocate_shared
.