More C++ Idioms/Checked delete

= Checked delete =

Intent
Increase the safety of the  expression.

Motivation and Sample Code
The C++ Standard allows, in 5.3.5/5, pointers to incomplete class types to be deleted with a delete-expression. When the class has a non-trivial destructor, or a class-specific operator delete, the behavior is undefined. Some compilers issue a warning when an incomplete type is deleted, but unfortunately, not all do, and programmers sometimes ignore or disable warnings.

In the following example,  can see the definition of. However,  calls , defined in  , which does not see the definition of  , but only forward declares it. Calling  on a partially defined type like this is undefined behavior which some compilers do not flag.

Solution and Sample Code
The Checked Delete idiom relies on calls to a function template to delete memory, which fails for declared but undefined types, rather than calls to.

The following is the implementation of boost::checked_delete, a function template in the Boost Utility library. It forces a compilation error by invoking the  operator on the parameterizing type,. If  is declared but not defined,   will generate a compilation error or return zero, depending upon the compiler. If  returns zero, checked_delete triggers a compilation error by declaring an array with -1 elements. The array name is type_must_be_complete, which should appear in the error message in that case, helping to explain the mistake.

NOTE: This same technique can be applied to the array delete operator as well.

WARNING: std::auto_ptr does not use anything equivalent to checked delete. Therefore, instantiating an auto_ptr using an incomplete type may cause undefined behavior in its destructor if, at the point of declaration of the auto_ptr, the template parameter type is not fully defined.

Known Uses

 * Boost's checked_delete.