Skip to content
Search

Boost::checked delete

lastmod 2015-06-23created 2015-06-232 edits

type_must_be_complete

What does type_must_be_complete inside boost/checked_delete.hpp mean?

template<class T> inline void checked_delete(T * x)
{
    // intentionally complex - simplification causes regressions
    typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
    (void) sizeof(type_must_be_complete);
    delete x;
}

The second line is a trick to keep the first line from disappearing. Otherwise the first line would be optimized away.

The reason the first line must not disappear is to produce an appropriate compile error. In particular, it is meant to catch an incomplete type that is only forward-declared and whose actual contents are not defined. delete can free a pointer to an incomplete type, but if, for example, the virtual destructor is declared "later", such a delete may behave unintentionally. The purpose of checked_delete is to turn this situation into a compile error outright.

Normally sizeof(T) itself should be an error in this case. Checking the value of sizeof(T) looks like a way of working around a compiler bug.

Favorite site