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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With