Search code examples
c++compound-literals

is this invalid C++?


struct HybridExpression {
    RawExpressionElement *ree;
    ExpressionNode *en;
};    

vector<HybridExpression> hexpression;

hexpression.insert(hexpression.begin() + starti, 
        (HybridExpression) {NULL, en}); 

gcc builds without warning but visual studio 2010 wont even compile it.

It doesnt like this bit: (HybridExpression) {NULL, en}


Solution

  • This is using a part of the C programming language that is not included in C++, it's called "compound literal". g++ -ansi will diagnose this, saying

    warning: ISO C++ forbids compound-literals

    This is not a part of C++0x.

    The C++0x compatible syntax would have been

    hexpression.insert(hexpression.begin() + starti, HybridExpression{NULL, en});
    

    To quote the C99 standard, paragraph 6.5.2.5:

    A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.