Incomplete Type

Last Updated: 2023-08-20 14:15:49 Sunday

-- TOC --

什么是incomplete type?

按照cppreference.com上面,以及一些网页的解释,简单地说,只要sizeof能够在编译期成功,就属于complete type,否则,就是incomplete type。

An incomplete type is an object type that lacks sufficient information to determine the size of the objects of that type. An incomplete type may be completed at some point in the translation unit. 由于缺少信息而无法计算其sizeof。(translation unit可以理解为一个cpp文件)

哪些type属于incomplete的:

测试代码:

#include <iostream>
using namespace std;

struct you;
extern int a[];

int main(void) {
    cout << sizeof(void) << endl;
    cout << sizeof(a) << endl;
    cout << sizeof(you) << endl;
    return 0;
}

编译时输出的warning和error:

$ g++ -Wall -Wextra test.cpp
test.cpp: In function ‘int main()’:
test.cpp:8:13: warning: invalid application of ‘sizeof’ to a void type [-Wpointer-arith]
    8 |     cout << sizeof(void) << endl;
      |             ^~~~~~~~~~~~
test.cpp:9:13: error: invalid application of ‘sizeof’ to incomplete type ‘int []’
    9 |     cout << sizeof(a) << endl;
      |             ^~~~~~~~~
test.cpp:10:13: error: invalid application of ‘sizeof’ to incomplete type ‘you’
   10 |     cout << sizeof(you) << endl;
      |             ^~~~~~~~~~~

只有sizeof(void)有点不符合前面对incomplete type的定义,gcc只它出了一个warning,去掉error后执行,还能得到sizeof(void)==1

我就没见过sizeof为0的时候...一个空的struct,它的sizeof也是1!

空struct定义如下:

struct xyz{};

本文链接:https://cs.pynote.net/sf/c/cpp/202301243/

-- EOF --

-- MORE --