class bass
{
public:
int a;
};
int main(int argc, char* argv[])
{
bass* ptr = new bass;
cout << ptr->a << endl;
bass *pp = new bass();
cout << pp->a << endl;
system("pause");
return 0;
}
new bass和new bass()是两种不同的初始化方式,前者为默认初始化(default initialization),后者为值初始化(value initialization)。
C++标准§8.5第11条:
An object whose initializer is an empty set of parentheses, i.e., (), shall be value- initialized.
C++标准§8.5第12条:
If no initializer is specified for an object, the object is default-initialized.
默认初始化(default initialization)
To default-initialize an object of type T means:
(7.1) — If T is a (possibly cv-qualified) class type, constructors are considered. The applicable constructors are enumerated, and the best one for the initializer () is chosen through overload resolution. The constructor thus selected is called, with an empty argument list, to initialize the object.
(7.2) — If T is an array type, each element is default-initialized.
(7.3) — Otherwise, no initialization is performed.
隐式定义的默认构造函数将会被调用,成员a是int类型,并不属于7.1(类类型)和7.2(数组类型)中的一种,所以a并没有被初始化,但是有一个不确定的值
值初始化(value initialization)
C++标准§8.5第8条:
To value-initialize an object of type T means:
(8.1) — if T is a (possibly cv-qualified) class type with either no default constructor or a
default constructor that is user-provided or deleted, then the object is default-initialized;
(8.2) — if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
(8.3) — if T is an array type, then each element is value-initialized;
(8.4) — otherwise, the object is zero-initialized.
bass类型的默认构造函数既没有被用户提供又没有被删除,所以一个被值初始化的bass对象会被零初始化(zero initialization)。
总结:对于有用户提供构造函数的类,不论有没有括号,都用构造函数进行初始化;如果没有构造函数,则不加括号的new只分配内存空间,不进行内存的初始化,而加了括号的new会在分配内存的同时初始化为0。