Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

c++14 - Are compound literals Standard C++?

Compound Literals are a C99 construct. Even though I can do this in 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. Yet all compilers I can get my hands on, compile the above mentioned code.

So is this a feature available in 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 )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is an extension that both gcc and clang support. The gcc document says:

As an extension, GCC supports compound literals in C90 mode and in C++, though the semantics are somewhat different in C++.

if you build with -pedantic you should receive a warning, for example clang says (see it live):

warning: compound literals are a C99-specific feature [-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:

In C++, a compound literal designates a temporary object, which only lives until the end of its full-expression. As a result, well-defined C code that takes the address of a subobject of a compound literal can be undefined in C++.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...