gpt4 book ai didi

c++ - 了解 C/C++ 中 "void"关键字的确切含义

转载 作者:可可西里 更新时间:2023-11-01 15:03:33 24 4
gpt4 key购买 nike

如前所述,例如,here , void 关键字主要有 3 种用途(有经验的 C/C++ 程序员可以跳到第 4 种用途):

1) 作为不返回任何内容的函数的返回类型。这个 将导致这样的代码示例:

void foo();
int i = foo();

生成编译器错误。

2) 作为函数参数列表中的唯一参数。 AFAIK,空函数的参数列表与编译器完全相同,因此以下两行的含义相同:(编辑:仅在 c++ 中为真。注释显示了 c 中的差异)。

int foo();
int foo(void);

3) void* 是一种特殊类型的通用指针——它可以指向任何未使用 const 或 volatile 关键字声明的变量,转换为/自任何类型的数据指针,以及指向所有非成员函数。此外,它不能被取消引用。我就不举例了。

还有第4种用法我没有完全理解:

4) 在条件编译中常用于表达式(void)0如下:

// procedure that actually prints error message 
void _assert(char* file, int line, char* test);
#ifdef NDEBUG
#define assert(e) ((void)0)
#else
#define assert(e) \
((e) ? (void)0 : \
__assert(__FILE__, __LINE__, #e))
#endif

我试图通过实验来理解这个表达式的行为。以下所有内容均有效(编译良好):

int foo(); // some function declaration
int (*fooPtr)(); // function pointer
void(foo);
void(fooPtr);
void(0);
(void)0;
void('a');
void("blabla");
exampleClass e; //some class named exampleClass with a default ctor
void(e);
static_cast<void>(e);

但这些不是:

void(0) // no semicolon
int i = void(0);

我能否由此得出结论,“void”(在第 4 次使用的上下文中) 只是一种特殊类型,任何类型都可以转换为它(无论是 c 风格还是 cpp-样式),它永远不能用作左值或右值?

最佳答案

Can I conclude from this that "void" (in the context of the 4th use) is simply a special type that any type can cast to it (whether it is c-style or cpp-style), and it can never be used as an lvalue or rvalue?

James McNellis 在 a comment above 中指出那void可以通过表达式 void() 用作右值.

他引用了当前的 C++ 标准:

C++11 §5.2.3/2:
“The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, which is value-initialized (no initialization is done for the void() case).”

这使得编写如下代码成为可能......

template< class T >
T foo() { return T(); }

并使用foo<void>() (我想很可能来自其他模板代码)。

正式void只是一个永远无法完成的不完整类型。

关于c++ - 了解 C/C++ 中 "void"关键字的确切含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8024790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com