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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…