在QScopedPointer的实现中使用sizeof

The use of sizeof in the implementation of QScopedPointer

本文关键字:sizeof 实现 QScopedPointer      更新时间:2023-10-16

为了理解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还不够吗?

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