Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ is it required to handle nullptr in user-defined and class-specific delete operators.?

Is it required for user-defined and class-specific delete operators to ignore nullptr as that operators from standard library do?


parallel discussion at google groups.

like image 857
Volodymyr Boiko Avatar asked Feb 03 '17 20:02

Volodymyr Boiko


People also ask

Does Nullptr check delete C++?

The C++ language guarantees that delete p will do nothing if p is null.

Do you have to delete a Nullptr?

Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.

Can we overload delete operator in C++?

Overloading New and Delete operator in c++ The new and delete operators can also be overloaded like other operators in C++. New and Delete operators can be overloaded globally or they can be overloaded for specific classes.

What does Nullptr do in C++?

The nullptr keyword represents a null pointer value. Use a null pointer value to indicate that an object handle, interior pointer, or native pointer type does not point to an object. Use nullptr with either managed or native code.


2 Answers

From [expr.delete],

If the value of the operand of the delete-expression is a null pointer value, it is unspecified whether a deallocation function will be called as described above.

So it sounds like your user defined or class specific delete operators to handle a nullptr.

Elsewhere in [class.free], when describing deallocation functions for classes, classes with virtual destructors can have the deallocation function called based on the dynamic type. In that case the deallocation function would not need to check for nullptr.

like image 124
1201ProgramAlarm Avatar answered Oct 10 '22 02:10

1201ProgramAlarm


From [basic.stc.dynamic]:

Any allocation and/or deallocation functions defined in a C++ program, including the default versions in the library, shall confrm to the semantics specified in 3.7.4.1 and 3.7.4.2.

From [basic.stc.dynamic.deallocation]:

The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.11), the deallocation function shall deallocate the storage referenced by the pointer, ending the duration of the region of storage.

It's required that the deallocation function have no effect if provided a null pointer value. That basically is the same thing as requiring that the deallocation function ignore null pionter values.

like image 44
Barry Avatar answered Oct 10 '22 02:10

Barry