Dmitriano
Dmitriano

Reputation: 2060

How std::shared_ptr is deallocated?

When does memory deallocation occur in the code below?

#include <memory>

int main()
{
    auto p = std::make_shared<int>(5);
    
    std::weak_ptr<int> wp = p;
    
    p = nullptr;
    
    return wp.lock() == nullptr ? 0 : 1;
}

As follows from this post std::make_shared performs one heap-allocation. Does this mean that until at least one std::weak_ptr is alive the memory can't be deallocated?

Upvotes: 9

Views: 1600

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598299

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_ptrs refer to the control block, but the control block itself is not freed until there are no more std::shared_ptrs or std::weak_ptrs 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

Upvotes: 3

SergeyA
SergeyA

Reputation: 62613

(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.

Upvotes: 4

Related Questions