在删除具有重载删除的对象之前进行NULL检查 [英] NULL check before deleting an object with an overloaded delete

查看:131
本文介绍了在删除具有重载删除的对象之前进行NULL检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码审查意见之一。



在调用任何对象的delete之前检查NULL是否是个好主意?



我明白在内部删除NULL运算符检查,并且是冗余的,但提出的参数是delete,因为运算符可以重载,如果重载版本不检查NULL可能会崩溃。所以是安全和合理的假设如果和当删除将重载它将检查NULL或不是?
在我的理解中,合理假设第一种情况,即重载删除将负责NULL检查,并且审查点不成立。你觉得怎么样?

解决方案

不,不要检查null。该标准说, delete(T *)0; 是有效的。它只是使你的代码复杂化没有好处。如果 operator delete 重载,最好在执行操作符时检查null。

在这里所有的答案都有一个缺失的部分,为了良心的缘故,让我在这里添加这最后一块。



标准实际上在[basic.stc.dynamic ],至少从C ++ 03开始:


在C ++程序中定义的任何分配和/该库应符合3.7.4.1和3.7.4.2中规定的语义。


其中引用的节以及一些其他地方在标准中列出的其他答案,说传递一个空指针的语义是一个无操作。


This came up as one of the code review comments.

Is it a good idea to check for NULL before calling delete for any object?

I do understand delete operator checks for NULL internally and is redundant but the argument put forth was delete as an operator can be overloaded and if the overloaded version doesn't check for the NULL it may crash. So is it safe and reasonable to assume that if and when delete will be overloaded it will check for the NULL or not? In my understanding its reasonable to assume the first case that overloaded delete shall take care of the NULL check, and the review point doesn't hold good. What do you think?

解决方案

No, don't check for null. The standard says that delete (T*)0; is valid. It will just complicate your code for no benefits. If operator delete is overloaded it's better to check for null in the implementation of the operator. Just saves code lines and bugs.

EDIT: This answer was accepted and upvoted, yet, in my opinion, it was not very informative. There is one missing piece in all answers here, and, for conscience sake, let me add this last piece here.

The standard actually says in [basic.stc.dynamic], at least since C++03:

Any allocation and/or deallocation functions defined in a C++ program, including the default versions in the library, shall conform to the semantics specified in 3.7.4.1 and 3.7.4.2.

Where the referenced sections, as well as some other places in the standard listed in other answers, say that the semantics of passing a null pointer are a no-op.

这篇关于在删除具有重载删除的对象之前进行NULL检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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