开发者

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

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

Is the (int *) ty开发者_如何学Pythonpe cast required?


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.


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.


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.


It is required because delete will call a destructor for each allocated element, even for int.

Consider this:

char * chars = new char[3];

delete [] (int*)chars;

What will happen? 3 destructors for int will be called. First one for memory address of &chars[0], second one for &chars[4] and third one for &chars[8]. Consider that &chars[4] and &chars[8] exceed the size of allocated memory. Even though int destructor in most if not all compilers is dummy it is wrong behaviour. And imagine if you write

delete [] (Foo*)chars;

where Foo has destructor and sizeof(Foo) > sizeof(char). Behaviour of your program will be undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜