Difference between new A and new A()

前端之家收集整理的这篇文章主要介绍了Difference between new A and new A()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

问题:
A是1个类,我们常常new1个A的对象,你常常会这么写:

A *pa = new A();

但是如果我这么写呢:

A *pa = new A;

二者有甚么区分吗? 这就是我们今天要讨论的问题。

先给出答案,再渐渐解释

If the class has a default constructor defined,then both are equivalent; the object will be created by calling that constructor.

If the class only has an implicit default constructor,then there is a difference. The first will leave any members of POD type uninitialised; the second will value-initialise them .

甚么是POD

POD的意思是 Plain Old Data,即1个class或struct没有构造函数、析构函数、虚函数。维基百科上这么描写:

A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members,has no user-defined destructor,no user-defined copy assignment operator,and no nonstatic members of pointer-to-member type.

int,char,wchar_t,bool,float,double are PODs,as are long/short and signed/unsigned versions of them.

pointers (including pointer-to-function and pointer-to-member) are PODs,
enums are PODs

a const or volatile POD is a POD.

a class,struct or union of PODs is a POD provided that all non-static data members are public,and it has no base class and no constructors,destructors,or virtual methods. Static members don’t stop something being a POD under this rule.

我们就定义1个POD的类:

class A { int m; };

再定义两个非POD类:

class B { ~B(); }; class C { C() : m() {}; int m; };

接下来就是使用了:

#include<iostream> using namespace std; class A { public: int m; }; class B { public: ~B() {}; public: int m; }; class C { public: C() : m() {}; public: int m; }; int main() { A *aObj1 = new A; A *aObj2 = new A(); cout << aObj1->m << endl; cout << aObj2->m << endl; B *bObj1 = new B; B *bObj2 = new B(); cout << bObj1->m << endl; cout << bObj2->m << endl; C *cObj1 = new C; C *cObj2 = new C(); cout << cObj1->m << endl; cout << cObj2->m << endl; delete aObj1; delete aObj2; delete bObj1; delete bObj2; delete cObj1; delete cObj2; return 0; }

输出
18780112
0
4522067
0
0
0

在所有C++版本中,只有当A是POD类型的时候,new A和new A()才会有区分

就是再看看如何判断是否是POD,不用认为判断:

#include <iostream> #include <type_traits> struct A { int m; }; struct B { int m1; private: int m2; }; struct C { virtual void foo(); }; int main() { std::cout << std::boolalpha; std::cout << std::is_pod<A>::value << '\n'; std::cout << std::is_pod<B>::value << '\n'; std::cout << std::is_pod<C>::value << '\n'; }

输出
true
false
false

猜你在找的PHP相关文章