Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
like image 337
blitzkriegz Avatar asked Nov 30 '22 09:11

blitzkriegz


2 Answers

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.

like image 55
Douglas Leeder Avatar answered Dec 05 '22 05:12

Douglas Leeder


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.

like image 31
James Avatar answered Dec 05 '22 07:12

James