在执行QScopedPointer时使用sizeof

时间:2018-07-25 05:40:47

标签: c++ qt sizeof qscopedpointer

要了解Qt如何防止不完整的类型,我浏览了qscopedpointer.h的头文件。相关部分如下:

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;
    }
};

我知道对不完整类型使用sizeof时编译会失败。但是数组和第二个sizeof会做什么?仅仅是sizeof还不够吗?

1 个答案:

答案 0 :(得分:1)

使用了一个数组,因此它的负大小将给出编译时错误。第二行通过确保使用sizeof(T)的实际大小来确保编译器不会跳过对IsIncompleteType的求值。