C++ Deleting Static Data

If the data is static, it isn't allocated on the heap, and it will be destructed during the shutdown of the process.

If it is a pointer to the data which is static, e.g.:

Something* MyClass::aPointer = new Something;

then like all other dynamically allocated data, it will only be destructed when you delete it. There are two frequent solutions:

  • use a smart pointer, which has a destructor which deletes it, or

  • don't delete it; in most cases, there's really no reason to call the destructor, and if you happen to use the instance in the destructors of other static objects, you'll run into an order of destruction problem.


static data means, it persists the entire duration of the program.

However, if you use static in pointer as:

static A *pA = new A();

then you can delete this, by writing delete pA. But that doesn't invalidate my first statement. Because the object which is being pointed to by the static pointer is not static. Its the pointer which is static, not the object which is being pointed to by the pointer.


You can place this class in std::unique_ptr. Then it will be deleted automatically on program shutdown. Otherwise memory leak tools will complain, that your class leaks. On the other hand this memory leak is harmless because the program finished running.