调用在堆栈上分配的变量的删除 [英] Calling delete on variable allocated on the stack
本文介绍了调用在堆栈上分配的变量的删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
忽略编程风格和设计,在堆栈上分配的变量上调用delete是否安全?
Ignoring programming style and design, is it "safe" to call delete on a variable allocated on the stack?
例如:
int nAmount;
delete &nAmount;
或
class sample
{
public:
sample();
~sample() { delete &nAmount;}
int nAmount;
}
推荐答案
否,调用 delete
在堆栈分配的变量。您只应在由 new
创建的内容上调用 delete
。
No, it is not safe to call delete
on a stack-allocated variable. You should only call delete
on things created by new
.
- 每个
malloc
或calloc
,应该只有一个free
。 - 对于每个
new
,应该只有一个delete
。 - 每个
new []
应该只有一个delete []
。 - 对于每个堆栈分配,不应显式释放或删除(在适用的情况下,析构函数会自动调用)。
- for each
malloc
orcalloc
, there should be exactly onefree
. - For each
new
there should be exactly onedelete
. - For each
new[]
there should be exactly onedelete[]
. - For each stack allocation, there should be no explicit freeing or deletion (the destructor is called automatically, where applicable).
一般来说,您不能混合使用任何这些(例如没有免费
-ing或 delete []
-ing a new
对象)。否则会导致未定义的行为。
In general, you cannot mix and match any of these (e.g. no free
-ing or delete[]
-ing a new
object). Doing so results in undefined behavior.
这篇关于调用在堆栈上分配的变量的删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文