C++ - destructors [closed]
In the external C++ learning resource that I'm reading.
What is an example on this statement?
When a variable goes out of scope, or a dynamically allocated variable is explicitly deleted using the delete keyword, the class destructor is called (if it exists) to help clean up the class before it is removed from memory.
And, what do we mean by dynamically allocat开发者_Go百科ed memory?
Thanks.
It's explained in your favorite C++ tutorial in section 6.9.
Examples
When a variable goes out of scope
void foo()
{
MyClass C;
C.callSomeMethod();
} // C is here going out of scope
or a dynamically allocated variable is explicitly deleted using the delete keyword
void foo()
{
MyClass* C = new MyClass; // allocating on heap
delete C; // deleting allocated memory
...
}
"dynamically allocated memory" means allocated via the new or new [] operator on the dynamical memory (usually the heap).
dynamically allocated memory is a memory you allocate by yourself (calloc\malloc\new etc.). if you allocate memory (dynamiclly) - you're also responsible for releasing in (free)
for example,
int i; --> the compiller allocate the memory (static)
char *c;
c = malloc (8*sizeof(char)); (dynamic)
in C++ when you want to release the memory of the object (destroy the object) you can implement a routine that will be called before the object will be destroyed (free routine). it can be useful (for example, in order to release some resources like closing files)
精彩评论