考虑以下具有用户定义的默认构造函数的类。
class TestClass {
public:
TestClass()
:data_(999) {
}
double getData() const {
return data_;
}
private:
double data_;
};
然后我们创建对象:
TestClass *p2 = new TestClass();
TestClass *p1 = new TestClass;
在任何条件下使用上述 2 个语句有什么区别吗?
谢谢,
最佳答案
简短回答:没有区别。
更长的答案:§5.3.4,15 指出
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.
§8.5,16 说
If the initializer is (), the object is value-initialized.
现在什么是值初始化和默认初始化,由 §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.
(强调我的)
总之,由于你的类有一个用户提供的默认构造函数,值初始化和默认初始化是相同的,所以两个新表达式给出相同的行为,即默认构造函数被调用。
这与 e.g. 不同。整数:
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.
关于c++ - 2 条语句用正则 new 表达式创建对象,有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16339811/