Why doesn#39;t delete set the pointer to NULL?(为什么不删除将指针设置为 NULL?)
问题描述
我一直想知道为什么在 delete 之后将指针自动设置为 NULL 不是标准的一部分.如果这一点得到处理,那么许多由于无效指针导致的崩溃就不会发生.但话虽如此,我可以想到标准会限制这一点的几个原因:
<块引用>性能:
附加指令可能会降低
delete的性能.可能是因为
const指针.然后,我猜标准本可以为这种特殊情况做一些事情.
有人知道不允许这样做的确切原因吗?
Stroustrup 本人 答案.摘录:
<块引用>C++ 明确允许执行删除归零一个左值操作数,我曾希望实现会做到这一点,但这个想法似乎没有受到实施者的欢迎.
但他提出的主要问题是,delete 的参数不必是左值.
I always wondered why automatic setting of the pointer to NULL after delete is not part of the standard. If this gets taken care of then many of the crashes due to an invalid pointer would not occur. But having said that I can think of couple of reasons why the standard would have restricted this:
Performance:
An additional instruction could slow down the
deleteperformance.Could it be because of
constpointers.Then again standard could have done something for this special case I guess.
Does anyone know exact reasons for not allowing this?
Stroustrup himself answers. An excerpt:
C++ explicitly allows an implementation of delete to zero out an lvalue operand, and I had hoped that implementations would do that, but that idea doesn't seem to have become popular with implementers.
But the main issue he raises is that delete's argument need not be an lvalue.
这篇关于为什么不删除将指针设置为 NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不删除将指针设置为 NULL?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
