Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

suppose the code does the following:

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

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

like image 724
Anycorn Avatar asked Apr 25 '10 18:04

Anycorn


People also ask

Can we delete void pointer in C?

It is not safe to delete a void pointer in C/C++ because delete needs to call the destructor of whatever object it's destroying, and it is impossible to do that if it doesn't know the type.

What does static_cast do in C?

static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int. The user of static_cast must make sure that the conversion is safe. The C-style cast does not perform any check, either at compile or at run time.

Why do we need static_cast in C++?

In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.


1 Answers

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

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined. (§5.3.5/3)

Then the footnote to this paragraph clearly states:

This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void (note 73).

like image 140
James McNellis Avatar answered Sep 18 '22 07:09

James McNellis