Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Deleting Static Data

Tags:

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.

like image 286
Ell Avatar asked Jul 27 '11 19:07

Ell


People also ask

Can static variables be deleted?

Yes, a user can delete it.

Do we need to delete static pointer?

@Ell: If your static object is a pointer to dynamically allocated memory, you should delete it, but oftentimes it is not strictly necessary.

How do you deallocate a static variable?

If the variable is of a reference type all that can be released is the memory of the object being held by that variable. When the class type containing the variable is loaded into memory the memory location for all static variables is allocated and it will only ever be deallocated when the class would be unloaded.

How do you destroy a static object in C++?

Static objects are declared with the keyword static. They are initialized only once and stored in the static storage area. The static objects are only destroyed when the program terminates i.e. they live until program termination.


1 Answers

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.

like image 65
James Kanze Avatar answered Oct 06 '22 00:10

James Kanze