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

后端 未结 6 1099
余生分开走
余生分开走 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 05:11

    No, they are the same. But there is a difference between:

    Test t;      // create a Test called t
    

    and

    Test t();   // declare a function called t which returns a Test
    

    This is because of the basic C++ (and C) rule: If something can possibly be a declaration, then it is a declaration.

    Edit: Re the initialisation issues regarding POD and non-POD data, while I agree with everything that has been said, I would just like to point out that these issues only apply if the thing being new'd or otherwise constructed does not have a user-defined constructor. If there is such a constructor it will be used. For 99.99% of sensibly designed classes there will be such a constructor, and so the issues can be ignored.

提交回复
热议问题