class A { public: A(int x) { } }; int main() { A *a = new A(1); A *b = new A;// 通过不了编译 return 0; }
当然如果A中有不带参数的构造函数时,两者的写法效果是一样的。 [解决办法] 没有区别 new A() 等于显式的告诉电脑说 我要申请一块内存存放一个 A类型的数据 并且调用没有参数的构造函数, [解决办法] 就没有人能勤快点去查查C++标准么,这个区别比较微妙比较小但是比较严重的。 [解决办法] new A;和new A();可能是不同的!
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: if T is a (possibly cv-qualified) non-POD class type (or array thereof), the object is default- initialized (8.5). If T is a const-qualified type, the underlying class type shall have a user-declared default constructor. — Otherwise, the object created has indeterminate value. I T is a const-qualified type, or a (possibly cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of const-qualified type, the program is ill-formed; — If the new-initializer is of the form (), the item is value-initialized (8.5);
8.5.5 To value-initialize an object of type T means: if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;