默认的默认构造函数会将变量初始化为零吗? [英] Does the defaulted default constructor initialize variables to zero?

查看:667
本文介绍了默认的默认构造函数会将变量初始化为零吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个类更新为C ++ 14,并尝试找出在构造时将所有实例变量初始化为零的最简单方法。这是我到目前为止的内容:

I'm updating a class to C++14, and trying to figure out the simplest way to initialize all of the instance variables to zero on construction. Here's what I have so far:

class MyClass {
public:
    int var;
    float* ptr;
    double array[3];
    MyStruct data;
    unique_ptr<MyStruct> smart_ptr;

    MyClass() = default;
    ~MyClass() = default;
}

将构造函数设置为 default 等同于:

Is setting the constructor to default the equivalent of doing:

MyClass() : var{}, ptr{}, array{}, data{}, smart_ptr{} {}

...还是我需要初始化每个变量? (我在Visual Studio中都尝试过,但是我都用零来表示,但是我不确定是否很幸运。)

... or do I need to init each variable? (I've tried both in Visual Studio and I get zeros either way, but I'm not sure if that's luck or not.)

我正在实例化该类不带括号: MyClass obj;

I'm instancing the class without brackets: MyClass obj;

推荐答案


正在将构造函数设置为默认的等效行为:

Is setting the constructor to default the equivalent of doing:

MyClass() : var{}, ptr{}, array{}, data{}, smart_ptr{} {}


否。

该行

MyClass() = default;

类似于但不完全等同于:

is more akin to but not exactly equivalent to:

 MyClass() {}

无论哪种情况,都使用

 MyClass obj;

会产生一个默认初始化的对象,其成员是默认初始化的。

results in a default-initialized object whose members are default initialized.

但是,则使用

 MyClass obj{};

obj 将被默认初始化为零构造函数,但仍将使用用户提供的默认构造函数对其进行默认初始化。

is that obj will be zero-initialized with the defaulted default constructor while it will be still default initialized with the user provided default constructor.

这篇关于默认的默认构造函数会将变量初始化为零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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