Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the correct type required for the delete operator in C++?

void * intptr = new int;
delete (int *) intptr;

Is the (int *) type cast required?

like image 291
Victor Avatar asked Sep 29 '11 00:09

Victor


3 Answers

Yes.

The type must match that which was new'd. The only time it doesn't have to match is deletion of a derived type through a base pointer, where the base type has a virtual destructor.

like image 199
GManNickG Avatar answered Nov 11 '22 04:11

GManNickG


Yes. Since C++ is not an everything-is-and-object language, the delete command must know the type of what you want to delete in order to know how to delete it.

like image 29
Idan Arye Avatar answered Nov 11 '22 05:11

Idan Arye


3 destructors for int will be called.

There's no such thing as a "destructor for int". delete/delete[] will only call a destructor for things that aren't POD or POD-class types.

like image 27
Nik Bougalis Avatar answered Nov 11 '22 04:11

Nik Bougalis