简体   繁体   English

在堆上分配时,在什么情况下(如果有的话)会发生“自动”清理,而在什么情况下不会发生?

[英]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++. 存储的类型以及对象是否为内置类型都是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. 在发布的两个示例中,必须调用delete[]delete释放动态分配的内存并调用需要调用的所有析构函数。

It is quite easy to remember. 这很容易记住。 Whenever a new is invoked a delete must be invoked. 每当调用new都必须调用delete方法。 Because new int[5] reserves 5 integers worth of memory on the heap, and this has to be freed ad some point. 因为new int[5]在堆上保留了5个整数的内存,因此必须在某个时候释放它。
The same goes for new Foo which reseves one Foo of memory on the heap. 对于new Foo也是如此,它重新占用了堆上的一个Foo内存。 (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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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