質問

Consider the following class with a user-defined default ctor.

class TestClass {
public:
    TestClass()
    :data_(999) {
    }
    double getData() const {
        return data_;
    }

private:
    double data_;
};

Then we create objects:

TestClass *p2 = new TestClass();
TestClass *p1 = new TestClass;

Any difference for using the 2 statements above in any condition?

Thank you,

役に立ちましたか?

解決

Short answer: No difference.

Longer answer: §5.3.4,15 states that

A new-expression that creates an object of type T initializes that object as follows:
— If the new-initializer is omitted, the object is default-initialized (§8.5); if no initialization is performed, the object has indeterminate value.
— Otherwise, the new-initializer is interpreted according to the initialization rules of §8.5 for direct-initialization.

And §8.5,16 says

If the initializer is (), the object is value-initialized.

Now what is value-initialization and default-initialization, is defined by §8.5,5-7:

To zero-initialize an object or reference of type T means:
if T is a scalar type (3.9), the object is set to the value 0 (zero), [...]
— if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
— if T is a (possibly cv-qualified) union type, the object’s first non-static named data member is zeroinitialized and padding is initialized to zero bits;
— if T is an array type, each element is zero-initialized;
— if T is a reference type, no initialization is performed.

To default-initialize an object of type T means:
if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called [...]
— if T is an array type, each element is default-initialized;
otherwise, no initialization is performed. [...]

To value-initialize an object of type T means:
if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called [...]
— if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
— if T is an array type, then each element is value-initialized;
otherwise, the object is zero-initialized.

(emphasis mine)

Together, since your class has a user provided default constructor, value initialization and default initialization is the same, so both new expressions give the same behavior, namely the default constructor is called.

It is a different thing with e.g. ints:

int *p2 = new int(); // value-initialized, i.e. zero-initialized, *p2 is 0
int *p1 = new int;   // default-initialized, i.e. no initialization. *p1 is some garbage. Or whatever.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top