开发者

C++ - destructors [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜