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

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » Difference between new A and new A()

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡