perhaps? 2009-03-06 19:39 采纳率: 100%
浏览 252
已采纳

类型名后面的括号是否对 new 有影响?

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

Test* test = new Test;

and

Test* test = new Test();

转载于:https://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new

  • 写回答

5条回答 默认 最新

  • 10.24 2009-03-06 21:01
    关注

    Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.

    Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

    • In C++1998 there are 2 types of initialization: zero and default
    • In C++2003 a 3rd type of initialization, value initialization was added.

    Assume:

    struct A { int m; }; // POD
    struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
    struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m
    

    In a C++98 compiler, the following should occur:

    • new A - indeterminate value
    • new A() - zero-initialize

    • new B - default construct (B::m is uninitialized)

    • new B() - default construct (B::m is uninitialized)

    • new C - default construct (C::m is zero-initialized)

    • new C() - default construct (C::m is zero-initialized)

    In a C++03 conformant compiler, things should work like so:

    • new A - indeterminate value
    • new A() - value-initialize A, which is zero-initialization since it's a POD.

    • new B - default-initializes (leaves B::m uninitialized)

    • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

    • new C - default-initializes C, which calls the default ctor.

    • new C() - value-initializes C, which calls the default ctor.

    So in all versions of C++ there's a difference between new A and new A() because A is a POD.

    And there's a difference in behavior between C++98 and C++03 for the case new B().

    This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序