TITLE: delete of an opaque type (Newsgroups: comp.std.c++) PROBLEM: jcarden@metronet.com (Jack Carden) Our group has undergone a significant development effort and recently paused to examine lessons learned. One of the points that came up regarding C++ was a group of bugs we identified relating to forward declarations and delete. It seems if one provides a forward declaration for a class, one can then invoke the delete operator on a pointer to an instance of that class without regard to the definition of the class. See, for example, the following fragment: class X; void foo(X *x) { delete x; } Similar code to this compiles and links and executes without noticeable side effects in our system using both the Sun Solaris and Dec Alpha C++ systems. It seems inconsistent to me that one could have defined a delete method and/or a destructor for class X which have now been totally bypassed. Is there some inherent reason why this choice is correct? Is this area considered in the C++ standard? We notice that new() is not supported for classes with a forward declaration. We use forward declarations in order to simplify include file nesting. [...] RESPONSE: clamage@Eng.sun.com (Steve Clamage), 3 Jun 1996 That issue is addressed in the draft standard in the section on "delete" expressions. It says: "If the object being deleted has incomplete class type at the point of deletion and the class has a non­trivial destructor or an allocation function or a deallocation function, the behavior is undefined." [ Centerline on SunOS diagnosis this as a warning. -adc ] New and delete in C++ are potentially dangerous, since all tradeoffs were made in the direction of allowing efficient implementations. (But new and delete are still less dangerous than malloc and free.) On the plus side, many errors in memory management can be caught by the compiler or runtime system. Since the behavior in the presence of errors is formally undefined, it means that implementations are free to provide all the checking that you might want. Indeed many implementations and third-party tools provide extensive checking of memory management, trading time and space for safety. In particular, it would be reasonable for a compiler to warn about deleting an object whose definition was not visible. Why isn't it always an error? The point was discussed, and sentiment was on the side of allowing the code because sometimes it is safe. If you took C code and replaced malloc/free with new/delete, you would then not also have to include struct definitions where they were not present before.