C++ 11:如果使用make_shared构造对象,如何删除对象

use*_*436 3 c++ reference-counting shared-ptr weak-ptr c++11

我遗漏了一些关于共享/弱指针的东西:

当使用shared_ptr构造a时make_shared,仅使用一个内存分配(为控制块和对象本身分配内存).当最后一次shared_ptr被摧毁但是还weak_ptr剩下什么时会发生什么?此时必须取消分配托管对象.但是如果分配的内存make_shared被释放,那将使弱指针无效,因为相同的释放会破坏控制块.

Ker*_* SB 8

使用make_sharedallocate_shared,只有一个包含对象本身的参考控制块.它看起来像这样:

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;
Run Code Online (Sandbox Code Playgroud)

该对象就地构建:::new (internal_memory.buf) T(args...).

整个块的内存分配::operator new,或者allocate_shared与分配器的allocate()功能一起分配.

当不再需要该对象时,会在对象本身上调用析构函数,例如internal_memory.buf->~T();.当不再需要参考控制块时,即当所有弱引用都消失以及所有弱引用时,参考控制块作为一个整体被释放::operator delete,或者具有分配器的deallocate()功能allocate_shared.