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
Note:
std::make_shared<T>()
creates a new heap-allocated instance of T, and wraps the pointer in a
std::shared_ptr<T>
.
This invokes the
copy-constructor, creating a new (heap-allocated) copy of your local (stack-allocated) object:
1 2 3
|
Customer customer = { 0, "John Doe", "[email protected]" };
auto cc = std::make_shared<Customer>(customer);
cc = nullptr; /* Destroys the heap-allocated copy owned by 'cc', the original 'customer' is uneffected */
|
You can avoid the copy and instead create the object directly on the heap:
This wraps the pointer to the local (stack-allocated) object in the
std::shared_ptr<T>
, which will obviously cause trouble:
1 2 3
|
Customer customer = { 0, "John Doe", "[email protected]" };
auto cc = std::shared_ptr<Customer>(&customer);
cc = nullptr; /* Whoops: This will attempt to delete the local (stack-allocated) object !!! */
|
Last edited on
Topic archived. No new replies allowed.