Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "x = new(Foo)" the same as "x = new Foo" for an arbitrary Foo?

I am looking at some legacy code and came across x=new(Foo); (note the parenthesis around the type supplied). I tested out variations and it appears to be the same as x=new Foo;

Foo is a non-POD data structure. Some external memory leak program is flagging the line - it's allocating memory for a CORBA out parameter so the caller should be taking care of the delete but that is a separate issue with many layers of indirection.

Is my analysis correct and is it acceptable style?

like image 790
joemooney Avatar asked Jan 16 '13 00:01

joemooney


2 Answers

It is correct, but the style is at least unusual.

Parentheses around a complete type name are sometimes allowed, but in this case are extraneous. It's like putting parentheses around an expression where not needed. Perhaps the closest analogy would be

return( 0 ); /* looks like a function, but isn't */

Confusingly, the parens are required for the sizeof operator, when passing it a type name but not when passing it an expression. Personally I see that as an inconsistency, and wouldn't choose to spread it to the rest of the language.

like image 97
Potatoswatter Avatar answered Oct 02 '22 07:10

Potatoswatter


If the name of the type has parentheses it must be enclosed in parentheses. Other types may be enclosed as well.

Example where parentheses are required:

new int(*[10])();    // parser error: parsed as (new int) (*[10]) ()
new (int (*[10])()); // OK: allocates an array of 10 pointers to functions

From cppreference.com: new expression

like image 29
Csq Avatar answered Oct 02 '22 05:10

Csq