Search code examples
c++memory-leaksstatic-membersdynamic-memory-allocation

Is it ok to skip delete for a dynamically-allocated static member variable?


Is it fine to define a static member variable as a newed object and never delete it? For example

class A
{
    static vector<BaseClass*> p;
};

vector<BaseClass*> A::p = vector<BaseClass*>{new DerivedClassA, ...};

I think there is no memory leakage problem because p is static, its life cycle is over the whole program and its memory will be released by the operating system when the program is terminated. Its memory behavior seems almost similar to the following

class A
{
    static vector<unique_ptr<BaseClass>> p;
};

vector<unique_ptr<BaseClass>> A::p = ...;

But I am not sure if I am right or not.


Solution

  • The problem with this approach is that even through the memory occupied by the BaseClass objects will be freed by the OS, ~BaseClass() will not be called. This could cause issues if these destructors do something important. But even if they don't, I still wouldn't recommend this. It will look fishy to anyone reading your code, and further, if you're using an IDE like Visual Studio that warns (can warn) you about memory leaks at shutdown, this sort of thing will make it yell at you. And if you get used to ignoring it when it yells at you, you'll miss a real problem eventually.