Arun
Arun

Reputation: 2373

variable number of arguments in constructor of int

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?

Upvotes: 2

Views: 302

Answers (2)

Casey
Casey

Reputation: 42554

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.

Upvotes: 0

Anand Rathi
Anand Rathi

Reputation: 786

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;
}

Upvotes: 1

Related Questions