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.
Yes, a user can delete it.
@Ell: If your static object is a pointer to dynamically allocated memory, you should delete it, but oftentimes it is not strictly necessary.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With