How std::shared_ptr is deallocated?
(Had to edit the answer since I have not read the question properly).
Yes, the memory itself will be around in your snippet, since you have allocated a single block for both control block and the object via make_shared
call.
std::make_shared<T>()
allocates a control block containing a constructed T
instance, and then returns a std::shared_ptr
that refers to that block. The T
instance is destructed when no more std::shared_ptr
s refer to the control block, but the control block itself is not freed until there are no more std::shared_ptr
s or std::weak_ptr
s referring to it. Which, in this example, is when both wp
and p
go out of scope when main()
exits:
#include <memory>
int main()
{
auto p = std::make_shared<int>(5);
std::weak_ptr<int> wp = p;
p = nullptr; // <-- the int is destroyed here
return wp.lock() == nullptr ? 0 : 1;
} // <-- the control block is freed here when p and wp are destroyed