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.
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."
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?