Making a shared_ptr out of a stack object corrupts the heap!!


Hi,


The following code is incorrect:

1
2
3
Customer customer = { 0, "John Doe", "[email protected]" };
auto cc = std::make_shared<Customer>(customer);
cc = nullptr;


it makes a pointer to the customer object (a stack allocated object) which is destroyed when cc = nullptr!!

Thus corrupting the heap!


Correct?

Regards,
Juan Dent
Not correct.

The line
 
auto cc = std::make_shared<Customer>(customer);
is more or less equivalent to
 
auto cc = std::shared_ptr<Customer>(new Customer(customer));

(the only difference is that make_shared might be more efficient because it can do a single memory allocation and store the reference counters together with the object)

In other words, it creates a heap allocated copy of customer.
Last edited on
Registered users can post here. Sign in or register to post.