简体   繁体   中英

When allocating on the heap, in which cases does “automatic” cleanup occur (if at all) and in which cases does it not?

I had heard that for primitives "automatic" cleanup occurs when they go out of scope, but that this does not happen for classes or structs. Is this true?

Ex:

int * i = new int[5];

vs

Foo * foo = new foo;

I've heard it both ways and am trying to determine which is correct.

I had heard that for primitives "automatic" cleanup occurs when they go out of scope, but that this does not happen for classes or structs. Is this true?

No, that is incorrect. The type of storage and whether an object is of built-in type or not are completely orthogonal concepts in C++. If an object has automatic storage, "cleanup" occurs when its scope is exited, regardless of its type.

In both examples posted, delete[] and delete must be called to free the dynamically allocated memory and call any destructors that need to be called.

It is quite easy to remember. Whenever a new is invoked a delete must be invoked. Because new int[5] reserves 5 integers worth of memory on the heap, and this has to be freed ad some point.
The same goes for new Foo which reseves one Foo of memory on the heap. (and then calls the constructor etc.)

To reserve memory on the stack you use this format:

{
  int fiveInts[5];
  Foo foo;
  //valid here
}
//foo's destructor has been called
//and fiveInts is out of scope (but has no destructor (practically speaking))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM