Are compound literals Standard C++?

后端 未结 2 1345
暗喜
暗喜 2020-11-29 07:19

Compound Literals are a C99 construct. Even though I can do this in C++ :

#include 
using namespace std;

int main() {
    for (auto i : (flo         


        
2条回答
  •  独厮守ぢ
    2020-11-29 08:02

    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++.

提交回复
热议问题