Checked Delete Idiom Question

closed account (3hM2Nwbp)
I've been reading about a bunch of idioms in the past few days, and I have a question about the checked delete idiom. Below is how the site explains the code example. My question is: In line 5 of the code, what is the point of calling sizeof() again if it would have made the compilation fail on line 4? Also, why is it being casted to void?


The checked delete idiom does not allow deletion of objects of partially defined type, but instead forces a compiler error if such a delete is invoked. The following is the implementation of checked_delete function template in boost. It forces a compiler error by declaring an array of negative elements if type T is not defined i.e. only a forward declaration is present. The use of sizeof() on a partially-defined type will either trigger a compiler error, or else return zero, which will lead to a compiler error for the illegal negative-size array.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<class T> 
inline void checked_delete(T * x)
{
    typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
    (void) sizeof(type_must_be_complete);
    delete x;
}
template<class T> 
struct checked_deleter : std::unary_function <T *, void>
{
    void operator()(T * x) const
    {
        boost::checked_delete(x);
    }
};
If the compiler did not throw an error for line 4 (returning 0 instead), then line 5 would catch the incomplete type because it would try to get the size of a negative array. Not all compilers will catch the error on line 4, which is why line 5 is there. The cast to void might be there to optimize it away(?)

All of this is explained in that last line:
"The use of sizeof() on a partially-defined type will either trigger a compiler error, or else return zero, which will lead to a compiler error for the illegal negative-size array."
Last edited on
closed account (3hM2Nwbp)
But would not T be an incomplete type as well - causing sizeof(T) to throw?
*Edit - oh....it's so clear now. Thanks
*Edit2 - But why is sizeof(type_must_be_complete) casted to void?
Last edited on
I'm not sure. Perhaps it's there to assure the compiler that the line is an empty statement so it will be optimized away.
closed account (3hM2Nwbp)
Alright, thanks for your time.
Topic archived. No new replies allowed.