C ++ delete static_cast <void *> (pointer) behavior

Suppose the code does the following:

T *pointer = new T(); delete static_cast<void*>(pointer); 

what is the result? Undefined, memory leak, memory deleted?

+4
source share
2 answers

The behavior is undefined. As for the delete expression, the C ++ standard says:

In the first alternative (delete an object), if the static type of the operand is different from its dynamic type, the static type should be the base class of the dynamic type of operands, and the static type should have a virtual destructor or undefined behavior. In the second alternative (delete array), if the dynamic type of the object to be deleted is different from its static type, the behavior is undefined. (Β§5.5.5 / 3)

The footnote to this paragraph then clearly states:

This means that the object cannot be deleted using a pointer of type void* , because there are no objects of type void (Note 73).

+7
source

Deleting with the void pointer is undefined, like any other action with the void pointer, except for explicitly converting it to another type of pointer.

+1
source

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


All Articles