Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c++ - Difference between A* pA = new A; and A* pA = new A();

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, but it seems that in both cases, the default constructor is called and only it. I'm looking for any difference about performance...

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...