c++ - &(int) { 1 } 在 C++ 中是什么意思?

标签 c++ c99

我看到了这个here我不知道这是什么意思:

&(int) { 1 }

我认为这很奇怪,因为它看起来像是无效的语法。它正在类型转换一个 block 范围(?),中间有一个随机的 1(没有分号)并获取地址。对我来说没有多大意义。各位大神能赐教吗?

用 C++11 试了一下,所以它可以编译:

auto a = &(int) { 1 };

但我不知道如何处理这个变量。

最佳答案

据我所知这是一个 compound literal ,它是 C99 特性,它是 not standard C++但 gcc 和 clang 都支持它作为扩展:

ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C90 mode and in C++, though the semantics are somewhat different in C++.

Usually, the specified type is a structure. Assume that struct foo and structure are declared as shown:

 struct foo {int a; char b[2];} structure;

Here is an example of constructing a struct foo with a compound literal:

 structure = ((struct foo) {x + y, 'a', 0});

This is equivalent to writing the following:

 {
   struct foo temp = {x + y, 'a', 0};
   struct

在这种情况下,a 的类型将指向 int。希望这最初是 C 代码,因为正如 gcc 文档所说:

In C, a compound literal designates an unnamed object with static or automatic storage duration. In C++, a compound literal designates a temporary object, which only lives until the end of its full-expression.

因此在 C++ 中获取地址可能不是一个好主意,因为对象的生命周期在完整表达式的末尾结束。虽然,它可能是仅依赖于未定义行为的 C++ 代码。

这是使用正确标志确实有很大帮助的情况之一,在 gcc 和 clang 中使用 -pedantic将产生警告和错误,例如 gcc 说:

warning: ISO C++ forbids compound-literals [-Wpedantic]
 auto a = &(int) { 1 };
                     ^
error: taking address of temporary [-fpermissive]

如果我们使用 -fpermissive 是 gcc,它确实允许此代码编译。尽管旧版本似乎允许使用 -Wno-address-of-temporary,但我无法在现代版本中使用任何标志构建此代码。我想知道 gcc 是否允许将其作为 remnant of an old extension .

注意,问题Cryptic struct definition in C对复合文字的使用非常有趣(取决于您对有趣的定义)。

假设 split is correctthis question是原始来源然后在示例中的代码中使用:

if (setsockopt(server_connection.socket, SOL_SOCKET, SO_REUSEADDR, &(int) { 1 }, sizeof(int)) < 0) {

在 C99 和 C++ 中都是有效的用法。

关于c++ - &(int) { 1 } 在 C++ 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41123558/

相关文章:

c - 我如何向 gcc 指定 C 中的 {} init 不应该编译?

c++ - 如何在不重载 `std::multiset` 、 `operator()` 、 `std::less` 的情况下为 `std::greater` 提供自定义比较器?

php - 对于从 C++ 开始的 php 开发人员,是否有一个地方可以让我们看到 PHP <=> C++ 等效库/函数?

c++ - 分层组件存储结构

c - C中两个集合的 union 和异或

c - 如何将无符号转换为 uint64_t?

c++ - 如何在 C++ (c++11/c++17) 中执行元组运算?

c++ - 如何在 Visual C++ 2008 中安装 SDL 库?

c - 为什么 printf ("%d%d%d",++i, i, i++) 是未定义的行为?

c - C99 是否保证数组是连续的?