Calling delete on variable allocated on the stack(在堆栈上分配的变量上调用 delete)
问题描述
忽略编程风格和设计,对分配在堆栈上的变量调用 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.
一般情况下,您不能混合搭配其中任何一种,例如没有 free
-ing 或 delete[]
-ing 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.
这篇关于在堆栈上分配的变量上调用 delete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在堆栈上分配的变量上调用 delete


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01