5

suppose the code does the following:

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

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anycorn
  • 50,217
  • 42
  • 167
  • 261
  • Practically speaking, the memory will be freed without any destructor being called. Of course, this isn't standard behavior. – zildjohn01 Apr 25 '10 at 18:31
  • The other possible result would be a failed compile, ideally that should be what happens but not sure if fails to compile. – CashCow Mar 08 '11 at 11:49

2 Answers2

8

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).

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Yep, `+1` from me. As for what _UB_ means: http://stackoverflow.com/questions/1553382/pod-freeing-memory-is-delete-equal-to-delete/1553407#1553407 `:)` – sbi Jan 13 '11 at 17:28
1

Deleting via a void pointer is undefined, as is doing anything else via a void pointer except explicitly converting it to another kind of pointer.