Ender
Ender

Reputation: 1778

Why does make_shared allocate same address in separate calls?

Why does this make_shared allocate the same memory address in two separate calls?

typedef struct {
    int a;
    int b;
    int c;
} test_t;

void call_func()
{
    std::shared_ptr<test_t> tst = std::make_shared<test_t>();

    std::cout << "addr: " << tst << std::endl;
}

int main()
{
    call_func();
    call_func();
}

Here it is online: http://coliru.stacked-crooked.com/a/ffc92bc131009402

Upvotes: 3

Views: 342

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595887

Because it can.

call_func() creates a new test_t object in available memory and wraps it inside a std::shared_ptr. The test_t object is destroyed when the std::shared_ptr goes out of scope when call_func() exits.

So, when the first call to call_func() exits, the memory that it used has been freed and is available for re-use when the second call to call_func() is made.

This is normal behavior, nothing to worry about.

Upvotes: 13

Related Questions