[C/C++] new operator… deeper….

There two type of using ‘new’ operator.

new Type(param);
new Type[size];

‘new’ is operator. So, parameter is followed by. Therefore, we should take care of using ‘()’.
Here is test result on MSVC7.


new (Typename(param)); // -- compile error
new (Typename)(param); // -- OK
new (Typename[size]);  // -- OK
new (Typename[size])(); // -- OK
new (Typename)[size];  // -- compile error
new (Typename[size])(param); // -- compile error

Interestingly, ‘Type[size]’ itself seems to be regarded as type. That is,

int a[10]; // 'sizeof(a)' works


Type[10]; // 'sizeof(Type[10])' works.

Considering ‘Type[size]’ as a kind of type may not be true. But, I think it’s similar with the case of pointer – pointer is type of not. Only to understand things easily, personally, I will regard it as type.

Let’s see (*1) from “C operator”‘s point of view – ‘new’ also a kind of operator.

operator new ( Typename(param) ); //  (*a)
operator new (Typename) (param); // (*b)
operator new (Typename[size]); // (*c)
operator new (Typename[size])(); // (*d)
operator new (Typename)[size]; // (*e)
operator new (Typename[size])(param) // (*f)

(*a) : ‘Type(param)’ is syntax for create instance. Not type name.
(*b) : ‘(param)’ is parameter of instance created by ‘(operator new(Typename))’
(*c) : ‘Typename[size]’ is just a type. So, no problem!
(*d) : same with above. It’s like “calling default constructor of newly created instance”.
(*e) : This is a form like “instance[size]” – (operator new (Typename))[size]. Array should be declard with type (Not instance).
(*f) : (operator new (Typename[size])) (param). This is like “calling constructor whose parameter is ‘(param)'”. But, ISO C++ forbids initialization in array new.

Hmmm….. Interesting…..


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s