为什么不删除将指针设置为 NULL? [英] Why doesn't delete set the pointer to NULL?

查看:29
本文介绍了为什么不删除将指针设置为 NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么在 delete 之后将指针自动设置为 NULL 不是标准的一部分.如果这一点得到处理,那么许多由于无效指针导致的崩溃就不会发生.但话虽如此,我可以想到标准会限制这一点的几个原因:

<块引用>

  1. 性能:

    附加指令可能会降低 delete 的性能.

  2. 可能是因为 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:

  1. Performance:

    An additional instruction could slow down the delete performance.

  2. 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆