delete NULL会怎样?

原文在此: Can you delete a NULL pointer?
没全转过来,只是留个记录。

根据目前的C++草案, Working Draft, Standard for Programming Language C++
Working Draft, Standard for Programming Language C++ 写道
5.3.5 (6): If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

它说如果不是空指针就调用析构函数。换句话说delete NULL;什么也不会发生。

不过delete一个指针并不会改变指针的值(不会在delete后将指针设为NULL),所以调用了delete之后最好自己把指针设为空指针,
delete ptr;
ptr = NULL;


===================================

Hmm,想起之前读到的一些可怕的代码。像这种:
if (flag == false) {
    // ...
}

这样写太容易出错了。习惯直接用!不好么……
if (!flag) {
    // ...
}

而if (flag == true)就更糟糕了……直接if (flag)就完事了嘛。

你可能感兴趣的:(C++,c,Blog,C#,gcc)