A * pA = new A;和A * pA = new A(); [英] Difference between A* pA = new A; and A* pA = new A();
问题描述
在C ++中,以下动态对象创建之间的确切区别是什么:
A * pA = new A;
A * pA = new A();
我做了一些测试,但似乎在这两种情况下,默认构造函数被调用, 。我正在寻找关于性能的任何差异...
感谢
如果 A
是POD类型,则 new A
将分配一个新的 A
对象,但留下一个不确定的值,否则 new A
会默认初始化 >
在所有情况下 new A()
会将值初始化<一个对象。
这对POD类型显然是不同的行为,但也影响非POD,非联合类类型,构造函数。
例如
struct A
{
int a;
std :: string s;
};
A
是非POD类类型没有用户声明的构造函数。当 A
是默认初始化时,调用隐式定义的构造函数,调用 s
(非POD类型),但 a
未初始化。
c> A 是值已初始化,因为它没有使用过的声明构造函数,其所有成员都是值初始化,这意味着默认构造函数 s
被调用, a
被初始化为零。
ISO 14882:2003参考资料:
-
5.3.4 [expr.new]如何初始化由
new
表达式分配的对象取决于是否省略初始化程序,一对圆括号或其他。 -
8.5 [dcl.init] / 5:零初始化,默认初始化和值初始化的含义
-
12.1 [class.ctor] / 7,8:与隐式定义的默认构造函数的行为匹配的用户编写的构造函数的形式。
/ li>
-
12.6.2 [class.base.init] / 4:如何初始化未在构造函数的成员初始化器列表中列出的基元和成员。
/ li>
in C++, what is the exact difference between both following dynamic object creations :
A* pA = new A;
A* pA = new A();
I did some tests, but it seems that in both cases, the default constructor is called and only it. I'm looking for any difference about performance...
Thanks
If A
is a POD-type, then new A
will allocate a new A
object but leave it with an indeterminate value, otherwise new A
will default initialize the new object.
In all cases new A()
will value initialize the new A
object.
This is obviously different behaviour for POD types but also affects non-POD, non-union class types without a used-declared constructor.
E.g.
struct A
{
int a;
std::string s;
};
A
is a non-POD class type without a user-declared constructor. When an A
is default initialized the implicitly defined constructor is called which calls the default constructor for s
(a non-POD type), but a
is not initialized.
When an A
is value initialized, as it has no used-declared constructor, all of its members are value initialized which means that the default constructor for s
is called and a
is zero initialized.
ISO 14882:2003 references:
5.3.4 [expr.new]/15: How objects allocated by a
new
expression are initialized depending on whether the initializer is omitted, a pair of parentheses or otherwise.8.5 [dcl.init]/5: The meaning of zero initialize, default initialize and value initialize.
12.1 [class.ctor]/7,8: The form of a user-written constructor that matches the behaviour of an implicitly defined default constructor.
12.6.2 [class.base.init]/4: How bases and members which are not listed in a member initializer list of a constructor are initialized.
这篇关于A * pA = new A;和A * pA = new A();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!