Thursday, July 9, 2009

How do you deallocate a static variable declared inside a C++ function?

Say, if you have:


int foo() {


static Bar* bar;


if (bar == NULL) {


bar = new Bar();


}


}





Question is, how do I clean up after the variable 'bar'?

How do you deallocate a static variable declared inside a C++ function?
As I understand it, a static variable in a function is a mechanism for the function to keep memory. I cannot give an example of that :( .





The problem understanding your code is, what are you using bar for, as it is not in the source you provided.





I.M.H.O, the static variable in a function would behave like any other static variable in the program, and would be destroyed automatically when the program is closed down. This would be done by the compiler, as it would have knowledge of the last reference, or usage, of the class concerned.
Reply:try





bar = NULL; // Should cleanup the memory





// Bar* will automatically be cleaned up when the program


// goes out of scope of the function.
Reply:The pointer will still bve there, but you can do


~bar; // deallocate memory


bar = 0; // Back to NULL





(something like that)
Reply:Ummm, What's that?! I didn't get bar == NULL. U mean if there is no pointer, pointing to bar, then allocate sth new?!... Well, why do u do that?... U know, static variables are with u to the end of the current page, available in the function they're declared in. So not u nor the compiler can cut the link between the address of the variable and the pointer I suppose.


Explain more, I've got some ideas but I dunno if u exactly mean what I think!...
Reply:bar, being a dynamically allocated object, can be cleaned up using the keyword delete. e.g.-





delete bar;


bar = 0;





As long as bar is the pointer to the memory you allocated, this should work no problem. Just saying -





bar = 0;





will cause the pointer bar to be 0, but the data it pointed to will still exist in the processes heap. This is a memory leak and is very bad.


No comments:

Post a Comment