c++ new带括号和不带括号

class bass
{
public:
    int a;
};

int main(int argc, char* argv[])
{
    bass* ptr = new bass;
    cout << ptr->a << endl;
    
    bass *pp = new bass();
    cout << pp->a << endl;

    system("pause");
    return 0;
}

new bass和new bass()是两种不同的初始化方式,前者为默认初始化(default initialization),后者为值初始化(value initialization)。

C++标准§8.5第11条:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value- initialized.

C++标准§8.5第12条:

If no initializer is specified for an object, the object is default-initialized.

默认初始化(default initialization)

To default-initialize an object of type T means:
(7.1) — If T is a (possibly cv-qualified) class type, constructors are considered. The applicable constructors are enumerated, and the best one for the initializer () is chosen through overload resolution. The constructor thus selected is called, with an empty argument list, to initialize the object.
(7.2) — If T is an array type, each element is default-initialized.
(7.3) — Otherwise, no initialization is performed.

隐式定义的默认构造函数将会被调用,成员a是int类型,并不属于7.1(类类型)和7.2(数组类型)中的一种,所以a并没有被初始化,但是有一个不确定的值

值初始化(value initialization)

C++标准§8.5第8条:

To value-initialize an object of type T means:
(8.1) — if T is a (possibly cv-qualified) class type with either no default constructor or a
default constructor that is user-provided or deleted, then the object is default-initialized;
(8.2) — if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
(8.3) — if T is an array type, then each element is value-initialized;
(8.4) — otherwise, the object is zero-initialized.

bass类型的默认构造函数既没有被用户提供又没有被删除,所以一个被值初始化的bass对象会被零初始化(zero initialization)。

总结:对于有用户提供构造函数的类,不论有没有括号,都用构造函数进行初始化;如果没有构造函数,则不加括号的new只分配内存空间,不进行内存的初始化,而加了括号的new会在分配内存的同时初始化为0。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值