C++ Deleting Static Data

Viewed 35958

If I have a class that contains private static data allocated on the heap that never changes, when, if at all, should I delete it?

As I understand it, a class itself is never constructed (because classes aren't first class objects in C++) then there is no destructor to delete the static data in? Im new at C++ so sorry if my understanding of c++ is fundamentaly flawed or if the answer is obvious! Thanks in advance, ell.

6 Answers

I have used this solution is to add a static function to deallocate the memory. Just that somewhere in the shutdown phase the caller needs to call this function. I am not sure this practice is good or bad; at least it does clean up the memory allocated on the heap. Glad to hear comments.

class example {
   public:
      static void dealloThing() { delete ptr; }
      /**
       * You could have more elaborate arguments to set special version
       * of Thing, here not elaborating the details
       */
      static void setThing(Thing* tptr) { ptr = tptr; }
   private:
      static Thing* ptr;
};

==== example.cpp ===
Thing* example::ptr=new Example();
Related