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
delete
performance.Could it be because of
const
pointers.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/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01