[英]Are compound literals Standard C++?
Compound Literals are a C99 construct. 复合文字是C99构建体。 Even though I can do this in C++ :
即使我可以在C ++中做到这一点:
#include <iostream>
using namespace std;
int main() {
for (auto i : (float[2]) {2.7, 3.1}) cout << i << endl;
}
It seems that for example MSVC supports it as an extension . 似乎MSVC例如支持它作为扩展 。 Yet all compilers I can get my hands on, compile the above mentioned code.
但是,我可以投入使用的所有编译器都可以编译上述代码。
So is this a feature available in C++14 ? 那么,此功能在C ++ 14中可用吗? Is there a different standard term (It looks to me like just creating a temporary using braced initialization) ?
是否有一个不同的标准术语(在我看来,这就像使用支撑初始化创建一个临时目录一样)?
Side Note : "Compound Literals" (or whatever I should call the above) are a pack expansion context ( just to mention a functionality ) 旁注 :“复合文字”(或上面我所说的任何东西)是包扩展上下文 (仅提及功能)
This is an extension that both gcc and clang
support. 这是gcc和
clang
支持的扩展。 The gcc document says: gcc文件说:
As an extension, GCC supports compound literals in C90 mode and in C++, though the semantics are somewhat different in C++.
作为扩展,GCC在C90模式和C ++中支持复合文字,尽管C ++中的语义有些不同。
if you build with -pedantic you should receive a warning, for example clang
says ( see it live ): 如果使用-pedantic进行构建,则应收到警告,例如
clang
表示( 实时查看 ):
warning: compound literals are a C99-specific feature [-Wc99-extensions]
警告:复合文字是C99特定的功能[-Wc99-extensions]
Note, the semantic differences in C++ are not minor and code that would be well-defined in C99 can have undefined behavior in C++ with this extension: 请注意,C ++中的语义差异并不小,在C99中可以良好定义的代码在具有此扩展名的C ++中可能具有未定义的行为:
In C++, a compound literal designates a temporary object, which only lives until the end of its full-expression.
在C ++中,复合文字指定了一个临时对象,该对象仅生存到其完整表达式的结尾。 As a result, well-defined C code that takes the address of a subobject of a compound literal can be undefined in C++.
结果,定义良好的C语言代码(使用复合文字的子对象的地址)可能无法在C ++中定义。
(float[2]) {2.7, 3.1}
is a C99 compound literal. 是C99复合文字。 Some compilers support it in C++ as an extension.
一些编译器在C ++中将其作为扩展支持。
float[2] {2.7, 3.1}
is a syntax error. 是语法错误。
Given using arr = float[2];
给定
using arr = float[2];
, ,
arr {2.7, 3.1}
is valid C++ that list-initializes a temporary array of two float
s. 是有效的C ++,它对两个
float
的临时数组进行列表初始化。
{2.7, 3.1}
is called a braced-init-list . 被称为braced-init-list 。
Finally, for your code, 最后,对于您的代码,
for (auto i : {2.7, 3.1}) cout << i << endl;
works equally well and is perfectly valid C++ - this constructs a std::initializer_list<double>
under the hood. 同样有效,并且是完全有效的C ++-这在
std::initializer_list<double>
构造了一个std::initializer_list<double>
。 If you really want float
s, add the f
suffix to the numbers. 如果确实需要
float
,则将f
后缀添加到数字中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.