Search code examples
c++c++11shared-ptrreference-countingweak-ptr

C++11: How is object deleted if it was constructed using make_shared


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.


Solution

  • With make_shared and allocate_shared, there's only one single reference control block that contains the object itself. It looks something like this:

    struct internal_memory_type
    {
        unsigned char[sizeof T] buf;   // make sure the object is at the top for
                                       // efficient dereferencing!
        // book keeping data
    } internal_memory;
    

    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 of allocate_shared with the allocator's allocate() 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's deallocate() function for allocate_shared.