Do std::weak_ptrs affect when the memory allocated by std::make_shared is deallocated?

后端 未结 2 465
生来不讨喜
生来不讨喜 2021-02-07 01:36

If I call std::make_shared (rather than just allocating a shared_ptr explicitly) then I expect the reference count to be allocated in

相关标签:
2条回答
  • 2021-02-07 01:55

    The common implementation is for the ref control block of an std::shared_ptr to contain both a strong and a weak reference count separately. The managed object is destroyed when the strong reference count goes to zero, but the ref control block itself is only released when the weak reference count also reaches zero.

    (When you use std::make_shared, the ref control block itself contains enough memory to hold the managed object. This is just a detail.)

    In other words, the observable behaviour for the managed object is independent of weak pointers.

    0 讨论(0)
  • 2021-02-07 01:59

    If you use make_shared and if the implementation uses a single allocation for both the object and the reference counts, then that allocation cannot be freed until all references (both strong and weak) have been released.

    However, the object will be destroyed after all strong references have been released (regardless of whether there are still weak references).

    0 讨论(0)
提交回复
热议问题