How to create temporary object in C++

This is another instance of the “everything that can be a declaration is a declaration” rule. [stmt.ambig]/p1:

There is an ambiguity in the grammar involving expression-statements
and declarations: An expression-statement with a function-style
explicit type conversion (5.2.3) as its leftmost subexpression can be
indistinguishable from a declaration where the first declarator
starts with a (. In those cases the statement is a declaration.

The standard provides the following examples:

Assuming T is a simple-type-specifier,

T(a)->m = 7;       // expression-statement
T(a)++;            // expression-statement
T(a,5)<<c;         // expression-statement
T(*d)(int);        // declaration
T(e)[5];           // declaration
T(f) = { 1, 2 };   // declaration
T(*g)(double(3));  // declaration

In the last example above, g, which is a pointer to T, is initialized
to double(3). This is of course ill-formed for semantic reasons, but
that does not affect the syntactic analysis.

and also:

class T {
// ...
public:
    T();
    T(int);
    T(int, int);
};

T(a);          // declaration
T(*b)();       // declaration
T(c)=7;        // declaration
T(d),e,f=3;    // declaration
extern int h;
T(g)(h,2);     // declaration

The simplest way to disambiguate is probably an extra set of parentheses. (A(a)); is unambiguously an expression-statement.

Leave a Comment