删除NULL但编译没有错误
我很困惑为什么下面的 C++ 代码可以编译。为什么调用delete 0 的方法不会产生任何错误?!
int *arr = NULL; // or if I use 0, it's the same thing
delete arr;
我确实尝试运行它,它根本没有给我任何错误......
I'm confused why the following C++ code can compile. Why does a call to delete the method of 0 not produce any error?!
int *arr = NULL; // or if I use 0, it's the same thing
delete arr;
I did try to run it, and it did not give me any error at all...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C++ 语言保证,如果 p 等于,则删除 p 将不会执行任何操作
无效的。
有关详细信息,请查看第 16.8,9 节此处 :
The C++ language guarantees that delete p will do nothing if p is equal to
NULL.
For more info, check out Section 16.8,9 here:
资源释放例程必须接受空指针参数并且不执行任何操作,这是 C 和 C++ 语言(不仅是它们)的事实上的标准。事实上,这是一个相当方便的约定。那么,真正的问题是:为什么它会让你感到惊讶?是什么让您认为它应该产生错误?此外,是什么让你认为它应该编译失败???
顺便说一句,你的问题,从它的表述方式来看,似乎没有多大意义,因为你的代码实际上无法编译。假定的指针声明缺少类型,这将使任何编译器发出诊断消息。
It is a de-facto standard in C and C++ languages (and not only in them) that resource deallocation routines must accept null-pointer arguments and simply do nothing. Actually, it is a rather convenent convention. So, the real question here: why does it surprize you? What makes you think that it should produce an error? Moreover, what makes you think that it should fail to compile???
BTW, your question, the way it is stated, doesn't seem to make much sense, since your code actually cannot compile. The supposed pointer declaration lacks a type, which will make any compiler to issue a diagnostic message.
NULL 和 0 不是同一件事。在 C++ 中,您应该使用 0。
删除空指针在语法上没有错误或不明确。事实上,根据定义,这是一个空操作;也就是说,删除第0个地址的操作相当于什么都不做。
NULL and 0 aren't the same thing. In C++ you should use 0.
There is nothing syntactically wrong or ambiguous about deleting the null pointer. In fact, this is by definition a no-op; that is, the operation of deleting the 0th address is equivalent to doing nothing at all.
尽管您的示例很简单,但编译器无法(在编译时)知道指针的值。
您还可以在编译时取消引用 null:
编译器不是为在编译时处理此类错误情况而构建的。
大多数(所有?)实现都将“删除 0”作为非操作。这段代码应该运行良好:
虽然我对此不是 100% 确定:)
Although your example is trivial, there is no way for a compiler to know (at compile time) the value of a pointer.
You can also dereference null at compile time:
Compilers aren't built to handle these kinds of error conditions at compile time.
And most (all?) implementations have 'delete 0' as a non-operation. This code should run fine:
Although I'm not 100% sure on that :)
您可以毫无问题地删除 NULL 指针,并且您可能/可能遇到的错误不会出现在编译时,而是出现在运行时。
通常这样做很方便:
You can delete a NULL pointer without problem, and the error you may/can have won't be at compilation time but at runtime.
Usually it's convenient to do :