3

Visual C++ has C4150 warning for cases when delete is applied to a pointer to incomplete type.

Such cases yield undefined behavior according to the Standard. AFAIK in Visual C++ they result in default operator delete() function and no destructor being called which allows for numerous bugs.

Now I could have used #prarma warning( error : 4150 ) in Visual C++ to treat that warning as error. I guess there're reasons why it is a warning and not an error by default in Visual C++.

In what real life code would I want to allow such cases? Why would I not switch that warning into a compiler error?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Does `void` count as an incomplete type? If yes, [this](http://stackoverflow.com/questions/6172232/is-it-undefined-behaviour-to-delete-a-null-void-pointer) may be relevant. :) – Xeo Oct 27 '11 at 15:06
  • You can never know what Microsoft meant with their products. – Daniel Oct 27 '11 at 15:06
  • Perhaps a class with trivial destructor? – Alok Save Oct 27 '11 at 15:06
  • I vaguely recall our product team hitting a bug in an older compiler version where no warning was generated at all for this error. For production code, why not just set the flag such that ALL warnings are errors and then use pragma to disable the warnings you consider to be benign? – selbie Oct 27 '11 at 15:12

2 Answers2

5

It's not always an UB.

If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
2

How about if the pointer is 0 (or nullptr in C++11)? delete 0; is by definition a no-op.

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • Does `0` count as an Incomplete type? – Alok Save Oct 27 '11 at 15:08
  • @Als: No, but `struct s; s* p = 0; delete p;` does. I just wanted to emphasize that it's the same as `delete 0;`. – Xeo Oct 27 '11 at 15:09
  • Ah okay..Ofcourse, This is the borderline case where the type is an Incomplete Opaque pointer but it points to `0`, so `delete`ing it is an No-Op. – Alok Save Oct 27 '11 at 15:11
  • @Als: See my linked question in the comment to the OP, there seems to be some controversity. :) *Edit*: Just saw you already commented that question when I first asked it, nvm then. :D – Xeo Oct 27 '11 at 15:12
  • Yes AFAIU, deleting a pointer of the type `void*` is an UB,but your in example, `p` has an type `struct` and not `void*`, so it is an legitimate borderline case. – Alok Save Oct 27 '11 at 15:15