开发者

C++: Checking for NULL on delete [duplicate]

This question already has answers here: 开发者_Python百科 Closed 12 years ago.

Possible Duplicate:

Test for void pointer in C++ before deleting

Is code snippet 1 equivalent to snippet 2?

//Snippet 1:
    delete record;          
    record = new Record;


//Snippet 2     
    if (record != NULL) 
    {
        delete record;
        record = NULL;
    }       
    record = new Record;


The only difference I can see is that if the Record constructor throws an exception, the first sample might leave the record variable set to the old deleted value, whereas in the second, it will be set to NULL.

EDIT:
Indeed the first sample, if repeated later, would lead to a double delete.

delete record;
record = new Record; // Throwing exception
// record points to old object
// ... later ...
delete record; // Double deletion - sky falls down etc.

The safe form would be:

delete record; record = 0;
record = new Record; // Can throw an exception if it likes

Or use a std::auto_ptr instead of a raw pointer.


It depends on the scope of record. If it's a class member and is deleted in the destructor then no, they're not the same. The first version can leave you with a double-delete issue (if new Record() throws) because record is not NULL.

If it has function-level scope then I think the second version is overkill.

The second version is more safe.


They are the same in that you have a new Record at the end of each, but snippet two has an unnecessary check for NULL prior to the delete.


The delete operator in C++ is required to work correctly (do nothing) when the pointer is NULL, so the two code fragments are the same. See http://opensource.devx.com/tips/Tip/14443, for example.


Yes, it is: delete on a NULL pointer is expected to work as in your latter code.

See $ 5.3.5:

2 If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section. In either alternative, the value of the operand of delete may be a null pointer value.


A nitpicking answer: The result is the same IF record is a pointer to record (with the caveats described in the other posts wrt. the record constructor throwing). If it's a class type with an implicit conversion to a pointer, the result might not be the same (because operators might be overloaded.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜