问题
Let we have procedure formed as class. Only constructor call makes some side effect. No need to handle class instance in memory after call. Following code instantiate that class:
struct A{
A(int){}
};
int main() {
A(0);//right. Pass const to ctor
int x=0;
A(x);//bad. Compiler interpret like A x;
(A(x));//right. New temporary object passed to brackets
A((int)x);//right. Pass temporary int to ctor
return 0;
}
(see also on Online IDE)
Why A(x); interpret as variable x declaration instead of temporary A object instantiaton?
回答1:
From the C++11 standard, ISO/EIC 14882 §6.8 [stmt.ambig] ¶1 (emphasis mine):
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.
To apply this to your question, A(x);
can parse as either "call the function A
/ construct a temporary object of type A
, and pass x
as the only function/constructor argument" or "declare a variable x
of type A
." The standard says that in this case, it should be parsed as a variable declaration.
Your other examples are not ambiguous because they cannot be parsed as a variable declaration, and so they are parsed as a call to A
's constructor.
回答2:
That's because what you consider should be the parameter list to the ctor, (x)
is being interpreted as "x
in parentheses". Thus, A(x)
is read as A (x)
is read as A x
.
In the other cases, the compiler has a hint suggesting that it should generate an A
instance, calling the ctor with the arguments supplied.
来源:https://stackoverflow.com/questions/29058769/c-temporary-class-instantiation-ambiguously