类型名称后面的括号与 new 有区别吗? [英] Do the parentheses after the type name make a difference with new?

查看:35
本文介绍了类型名称后面的括号与 new 有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果'Test'是一个普通的类,有什么区别:

If 'Test' is an ordinary class, is there any difference between:

Test* test = new Test;

Test* test = new Test();

推荐答案

让我们学究,因为有些差异实际上会影响您的代码行为.以下大部分内容摘自对旧的新事物"文章的评论.

Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.

有时new运算符返回的内存会被初始化,有时则不会,取决于你新建的类型是否为POD(纯旧数据),或者它是包含 POD 成员并使用编译器生成的默认构造函数的类.

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • 在 C++1998 中有两种类型的初始化:零和默认
  • 在 C++2003 中,添加了第三种类型的初始化,即值初始化.

假设:

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

在 C++98 编译器中,应该发生以下情况:

In a C++98 compiler, the following should occur:

  • new A - 不确定值
  • new A() - 零初始化

  • new A - indeterminate value
  • new A() - zero-initialize

new B - 默认构造(B::m 未初始化)

new B - default construct (B::m is uninitialized)

new B() - 默认构造(B::m 未初始化)

new B() - default construct (B::m is uninitialized)

new C - 默认构造(C::m 为零初始化)

new C - default construct (C::m is zero-initialized)

在符合 C++03 的编译器中,事情应该是这样的:

In a C++03 conformant compiler, things should work like so:

  • new A - 不确定值
  • new A() - 值初始化 A,因为它是一个 POD,所以它是零初始化.

  • new A - indeterminate value
  • new A() - value-initialize A, which is zero-initialization since it's a POD.

new B - 默认初始化(使 B::m 未初始化)

new B - default-initializes (leaves B::m uninitialized)

new B() - 值初始化 B,它对所有字段进行零初始化,因为它的默认构造函数是编译器生成的,而不是用户定义的.

new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

new C - 默认初始化 C,它调用默认的构造函数.

new C - default-initializes C, which calls the default ctor.

所以在所有版本的 C++ 中,new Anew A() 之间是有区别的,因为 A 是一个 POD.

So in all versions of C++ there's a difference between new A and new A() because A is a POD.

对于 new B() 的情况,C++98 和 C++03 之间的行为存在差异.

And there's a difference in behavior between C++98 and C++03 for the case new B().

这是 C++ 尘土飞扬的角落之一,可以让您发疯.在构造对象时,有时您需要/需要括号,有时您绝对不能拥有它们,有时则无关紧要.

This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.

这篇关于类型名称后面的括号与 new 有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆