Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 203
user2052436 Avatar asked Jan 13 '23 12:01

user2052436


1 Answers

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.

like image 55
Kerrek SB Avatar answered Jan 16 '23 18:01

Kerrek SB