分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow
问题:
A是一个类,我们经常new一个A的对象,你经常会这么写:
A *pa = new A();
- 1
但是如果我这么写呢:
A *pa = new A;
- 1
两者有什么区别吗? 这就是我们今天要讨论的问题。
先给出答案,再慢慢解释
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,即一个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.
- 1
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.
我们就定义一个POD的类:
class A{ int m;};
- 1
- 2
- 3
- 4
再定义两个非POD类:
class B { ~B(); }; class C { C() : m() {}; int m; };
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
接下来就是使用了:
#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;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
输出:
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';}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
输出:
true
false
false
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow