Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is boost::checked_delete "intentionally complex"?

Tags:

So I was looking through some boost source code and came across this:

(from <boost/checked_delete.hpp>)

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;
}

Anyone happen to know why it is implemented in this way? Wouldn't sizeof(T) (for example) already be enough?

like image 632
pushingbits Avatar asked Jul 23 '11 17:07

pushingbits


2 Answers

Someone asked the same question earlier. This post written by Peter Dimov (one of the writers of boost/checked_delete.hpp) pretty much speaks for itself:

  • What's the result of applying sizeof to an incomplete type?

A compile-time error, unless the compiler chooses to return 0 as a nonstandard extension.

  • Why is sizeof called twice?

The second sizeof is a workaround for a Metrowerks CodeWarrior bug in which the first typeof is never instantiated unless used.

  • Why is the result of sizeof cast to void? What exactly does that line do?

Silences a compiler warning.

like image 163
In silico Avatar answered Sep 29 '22 18:09

In silico


This is just a guess; but there may be compilers out there that just emit a warning when you write sizeof(incomplete_type) and return 0. So you're making sure the array declaration fails in that case by trying to declare an array of size -1.

like image 20
Praetorian Avatar answered Sep 29 '22 18:09

Praetorian