سؤال

Possible Duplicate:
Do the parentheses after the type name make a difference with new?

I saw someone uses the constructor like this:

class Foo
{
  public: Foo();
};

int main(){
  Foo *f= new Foo;
}

what is the difference between Foo *f= new Foo; and Foo *f= new Foo(); ?

هل كانت مفيدة؟

المحلول

First of all the code you give will not compile. You need to have

Foo* f = new Foo()

Notice the asterisk.

Otherwise the two calls have the same result for non-primitive types. I have worked in companies where the () syntax is enforced by the styleguide and for a good reason: for primitive types there can be a difference:

int* p = new p;
cout << *p << endl; // the value is arbitrary i.e. behavior is undefined.
int* q = new int();
cout << *q << endl; // outputs 0.

It may be obvious here but imagine that Foo is a typedef for instance. So my advice is: always use the Foo() syntax.

نصائح أخرى

There is no difference between those two forms of initializations. Both will call the default constructor, given that the constructor is public.

Ỳour example probably even won't compile, you need to declare a pointer

 Foo *f = new Foo;

and there is no difference in typing new Foo or new Foo() since both run the constructor with no arguments.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top