Difference between A* pA = new A; and A* pA = new A();

后端 未结 4 973
野趣味
野趣味 2020-12-02 17:43

in C++, what is the exact difference between both following dynamic object creations :

A* pA = new A;

A* pA = new A(); 

I did some tests,

相关标签:
4条回答
  • 2020-12-02 18:06

    The lexer will have to scan two characters less in the first version, so the compilation process is a little faster ;)

    0 讨论(0)
  • 2020-12-02 18:07

    If A is a POD-type, then new A will allocate a new A object but leave it with an indeterminate value, otherwise new A will default initialize the new object.

    In all cases new A() will value initialize the new A object.

    This is obviously different behaviour for POD types but also affects non-POD, non-union class types without a used-declared constructor.

    E.g.

    struct A
    {
        int a;
        std::string s;
    };
    

    A is a non-POD class type without a user-declared constructor. When an A is default initialized the implicitly defined constructor is called which calls the default constructor for s (a non-POD type), but a is not initialized.

    When an A is value initialized, as it has no used-declared constructor, all of its members are value initialized which means that the default constructor for s is called and a is zero initialized.

    ISO 14882:2003 references:

    • 5.3.4 [expr.new]/15: How objects allocated by a new expression are initialized depending on whether the initializer is omitted, a pair of parentheses or otherwise.

    • 8.5 [dcl.init]/5: The meaning of zero initialize, default initialize and value initialize.

    • 12.1 [class.ctor]/7,8: The form of a user-written constructor that matches the behaviour of an implicitly defined default constructor.

    • 12.6.2 [class.base.init]/4: How bases and members which are not listed in a member initializer list of a constructor are initialized.

    0 讨论(0)
  • 2020-12-02 18:15

    please see STL implementing code (e.g. allocator) then you'll understand.

    0 讨论(0)
  • 2020-12-02 18:23

    It's exactly the same, also performance wise :)

    0 讨论(0)
提交回复
热议问题