1

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?

Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
Zhilei Han
  • 13
  • 4

1 Answers1

1

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.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • thx, does this mean some compilers evaluate an incomplete type to be 0-sized? – Zhilei Han Jul 25 '18 at 06:11
  • i'm not sure if that `sizeof`-expression has a value at all for the compiler. msvc gives *error C2027: use of undefined type T* \*and\* *error C2118: negative subscript* – Swordfish Jul 25 '18 at 06:59