C ++: checking for NULL on deletion

Possible duplicate:
Test 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; 
+4
source share
6 answers

The only difference I see is that if the Record constructor throws an exception, the first pattern can leave the Record variable equal to the old remote value, while in the second it will be set to NULL .

EDIT:
Indeed, the first sample, if repeated later, will lead to double deletion.

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

Safe form:

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

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

+8
source

It depends on the amount of recording. If it is a member of the class and is deleted in the destructor, then no, they do not match. The first version may leave you with the problem of double deletion (if a new record () is thrown away) because the record is not NULL.

If it has a functional level domain, I think the second version is redundant.

The second version is more secure.

+6
source

They coincide with the fact that you have a new entry at the end of each, but the second fragment has an unnecessary check for NULL before deleting.

+3
source

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

+1
source

Yes it is: delete on a NULL pointer is expected to work as in the last code.

See section 5.3.5:

2 If the operand is of class type, the operand is converted to a pointer type by calling the above conversion and the converted operand is used instead of the original operand for the rest of this section. In any alternative, the value of the delete operand may be a null pointer value.

+1
source

The answer to the question: the result of the same IF record is a pointer to the record (with reservations described in other posts regarding the metadata of the record constructor). If it is a class type with an implicit pointer to conversion, the result may not be the same (since operators may be overloaded.)

+1
source

Source: https://habr.com/ru/post/1337132/


All Articles