据我可以告诉这是一个
compound literal,它是C99的功能,它是
not standard C++,但是gcc和铛支持它作为一个扩展:
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:
06000
Here is an example of constructing a struct foo with a compound
literal:
06001
This is equivalent to writing the following:
06002
在这种情况下,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有一个非常有趣(取决于你有趣的定义)复合字面量的使用。
假设Schism is correct和this question是原始源,那么在示例中的代码中的使用:
if (setsockopt(server_connection.socket, SOL_SOCKET, SO_REUSEADDR, &(int) { 1 }, sizeof(int)) < 0) {
是在C99和C中的有效使用。