C++ - destructors [closed]

走远了吗. 提交于 2019-12-25 21:09:10

问题


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 allocated memory?

Thanks.


回答1:


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
...
}



回答2:


It's explained in your favorite C++ tutorial in section 6.9.




回答3:


"dynamically allocated memory" means allocated via the new or new [] operator on the dynamical memory (usually the heap).




回答4:


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)



来源:https://stackoverflow.com/questions/4773990/c-destructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!