Deleting a Shared Pointer Twice

What happens if I manually delete a shared pointer twice using the delete keyword?

If you attempt to manually delete a shared pointer twice, like this:

#include <memory>

int main() {
  auto Pointer{std::make_shared<int>(42)};
  delete Pointer.get();
  delete Pointer.get();
}

You will encounter undefined behavior. The shared pointer is designed to automatically manage the lifetime of the object it points to. When the last shared pointer owning the object is destroyed, the object is automatically deleted.

By manually deleting the pointer, you interfere with this mechanism. The first manual delete will free the memory, and the second attempt to delete it will be operating on memory that has already been freed.

This can lead to crashes, memory corruption, or other undesirable results.

The correct approach is to simply allow the shared pointers to manage the object lifetime for you:

#include <iostream>
#include <memory>

int main() {
  auto Pointer{std::make_shared<int>(42)};
  std::cout << *Pointer;
}
42

When Pointer goes out of scope at the marked line, the int is automatically deleted, with no manual intervention required.

Shared Pointers using std::shared_ptr

An introduction to shared memory ownership using std::shared_ptr

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Creating a shared_ptr to this
Is it okay to create a shared_ptr from the this pointer?
Polymorphism with Shared Pointers
How do shared pointers handle polymorphism? Can I store derived class objects in a shared_ptr of base class type?
Shared Pointers in Multithreaded Environments
Are shared pointers thread-safe? Can they be used in multithreaded applications?
Shared Pointer Cyclic References
What happens if two shared pointers reference each other? Will this cause a memory leak?
When to Use Shared Pointers
In what situations should I use shared pointers instead of unique pointers or raw pointers?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant