To understand how Qt prevent incomplete type I went through the header file of qscopedpointer.h
.The related part is as follows:
template <typename T>
struct QScopedPointerDeleter
{
static inline void cleanup(T *pointer)
{
// Enforce a complete type.
// If you get a compile error here, read the section on forward declared
// classes in the QScopedPointer documentation.
typedef char IsIncompleteType[ sizeof(T) ? 1 : -1 ];
(void) sizeof(IsIncompleteType);
delete pointer;
}
};
I know when using sizeof
on incomplete type the compilation will fail.But what do the array and second sizeof
do? Is sizeof alone not enough?
An array is used so the negative size of it will give a compile time error. The second line makes sure the compiler can't skip the evaluation of sizeof(T)
by ensuring the actual size of IsIncompleteType
is used.