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

后端 未结 6 1070
余生分开走
余生分开走 2020-11-21 04:15

If \'Test\' is an ordinary class, is there any difference between:

Test* test = new Test;

and

Test* test = new Test();
         


        
6条回答
  •  执笔经年
    2020-11-21 04:54

    new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don't mind if the constructor isn't called.

    If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };) then new Thing; is like malloc(sizeof(Thing)); whereas new Thing(); is like calloc(sizeof(Thing)); - it gets zero initialized.

    The gotcha lies in-between:

    struct Thingy {
      ~Thingy(); // No-longer a trivial class
      virtual WaxOn();
      int i;
    };
    

    The behavior of new Thingy; vs new Thingy(); in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.

提交回复
热议问题