2

I wrote the following code snippet which resulted in compilation errors when executed on codepad.org

int main()
{
int *p = new int(5,6,7);
return 0;
}

I was passing 3 number of arguments to constructor of int while dynamically allocating memory for it.(which should not work according to me).

But when I executed the same code in visual studio 2010 compiler it is compiling and initializing the value with the last argument. Why is this working like this?

Arun
  • 2,247
  • 3
  • 28
  • 51

2 Answers2

1

VS2010 is invoking commo operator and rightly assigning the last value.

http://en.wikipedia.org/wiki/Comma_operator

For gcc try this

int main()
{
 int *p = new int((5,6,7));
 return 0;
}
Anand Rathi
  • 790
  • 4
  • 11
0

VS2010 is non-conforming (surprise). The (5,6,7) in new int(5,6,7) is a new-initializer. According to C++11 §5.3.4/15:

A new-expression that creates an object of type T initializes that object as follows:

  • If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value.

  • Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.

and §8.5/13 states:

If the entity being initialized does not have class type, the expression-list in a parenthesized initializer shall be a single expression.

The expression-list in your example 5,6,7 has multiple expressions, so compilers should diagnose this as an error.

Community
  • 1
  • 1
Casey
  • 41,449
  • 7
  • 95
  • 125
  • I think that 'single expression' is being treated as comma operator , I think which may be a right behaviour , I am not sure though. – Anand Rathi Jul 22 '13 at 05:58
  • @AnandRathi It's not a single expression, it's multiple expressions separated by a comma - it would have to be for the comma operator to even apply. I agree with you that VS2010 is interpreting this new-initializer in that way, but it's clearly non-conforming behavior. – Casey Jul 22 '13 at 14:16