use*_*836 2 c++ types void incomplete-type
我是整体编程的新手.
我已经尝试阅读该语言的官方标准,但无法找到我的问题的任何答案.
所以我需要了解在C++中void类型和其他不完整类型之间的主要区别.例如:语言(或代码)中是否存在我们可以使用void而不是其他不完整类型的位置,反之亦然?或者像其他各种不完整类型一样无效?
在void和另一个不完整类型之间确实有一个非常微妙的区别:
您不能引用void类型:
struct T; // incompletely defined type
// incompletely defined types and void are incomplete types
T* x=nullptr; // pointer to incomplete type are valid, same for void pointers
T& tref=*x; // it's valid to have a reference to an incompletely defined type
void& vref; // it's INVALID to have a reference to void, because no object could ever be void
int f(void &vt); // INVALID function declaration with invalid parameter: void reference
int g(T& vt); // valid function declaration using a parameter: reference to incomplete type
Run Code Online (Sandbox Code Playgroud)
C++标准报价:
3.9/5:已声明但未定义的类,或未知大小或元素类型不完整的数组,是未完全定义的对象类型.未完全定义的对象类型和void类型是不完整的类型
3.9/8: 对象类型是(可能是cv限定的)类型,它不是函数类型,不是引用类型,也不是void类型.
8.3.2/1: 指定类型"对cv void的引用"的声明符是格式错误的.
可以将任何表达式转换为void,这显然不是其他不完整类型的情况:
(void)(3 + 5); // OK explicit conversion to void
(T)(3 + 5); // Invalid expression to an incomplete type
Run Code Online (Sandbox Code Playgroud)
这在C++标准中有记录:
3.9.1/9:任何表达式都可以显式转换为cv void类型