Possible Duplicate:
Most vexing parse: why doesn't A a(()); work?
I am having this simple C++ issue that is making me wanna restart my CS degree all over again trying to learn something this time. ;)
Why this code doesn't compile:
vector<int> v(int());
v.push_back(1);
while this other one compiles without a single warning
vector<int> v((int()));
v.push_back(1);
It's even hard to find a difference at all (extra parenthesis were added :P).
It's called the most vexing parse.
vector<int> v(int());
Declares a function v
that takes a function (taking no parameters returning an int
) and returns a vector<int>
. This is automatically "adjusted" to a function v
that takes a pointer to a function (taking no parameters returning an int
) and returns a vector<int>
.
The extra pair of parentheses inhibits this interpretation as you can't place extra parentheses around parameter declarators in function declarations so (int())
can only be interpreted as an initializer for an object named v
.
C++ has an explicit disambiguation rule that prefers to parse things (in this case int()
) as declarators rather than expressions if it makes syntactic (but not necessarily semantic) sense.
Indeed its a function declaration. See: http://www.gotw.ca/gotw/075.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With