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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With