Re: Can static memory be deleted
Zedzed wrote:
Hi
I have a very simple question: Can a static pointer be deleted?
Yes it can, but your code must be able to deal with it correctly.
For example:
int main(int argc, char* argv[])
{
static X* p = new X();
...
delete p;
}
This code is ok because p is initialized only once, and deleted only
once. If it were any other function besides main(), however, I'd call
it a very dangerous way to code because future invocations may make use
of the dangling pointer. (In that case you'd want to reset the pointer
to null, and be sure that you test for null before using the pointer,
or make the pointer be non-static.) But what is the purpose for making
this static anyway? Why not use a normal (non-static) auto_ptr to
guarantee automatic deletion and works even if exceptions are thrown.
(Let's overlook that this is main and an exception escaping from main
uncaught will terminate the program anyway...)
Finally, yes, at shutdown the program will cleanup static variables,
but for pointers, it only cleans up the pointer, not the object to
which it points. If you don't delete the object, it will be leaked.
The os will reclaim memory, but not necessarily all resources, so it's
not a good idea to depend on this.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]