显式默认的构造函数和成员变量的初始化 [英] Explicitly defaulted constructors and initialisation of member variables

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

问题描述



以下两个代码示例是否相同?


$

b $ b

Y 是否有任何约束可以使用第一个选项?

  class X 
{
public:
X()= default;

private:
Y m_y;
};

class X
{
public:
X():m_y(){}

private:
Y m_y ;
};


解决方案

有两种可能的差异来源。 >


  1. X()= default; 不是用户提供。 X():m_y(){} 是。前者可以琐碎;后者从来不是微不足道的。此外,如果 X 对象是值初始化的,它们的行为会有所不同。


  2. X()= default; 执行的操作等效于 X(){} -initializes m_y X():m_y(){} value-initializes m_y 。根据 Y 的不同,这可能不同。例如,如果 Y int ,则默认初始化将使其保持不确定值,而值初始化将其设置为零。



I'm slightly confused about what happens when a ctor is explicitly defaulted.

Are the two code samples below equivalent?

Are there any constraints on Y to be able to use the first option?

class X
{
public:
    X() = default;

private:
    Y m_y;
};

class X
{
public:
    X() : m_y() {}

private:
    Y m_y;
};

解决方案

There are two possible sources of differences.

  1. X() = default; is not user-provided. X() : m_y() {} is. The former can be trivial; the latter is never trivial. Also, they will behave differently if an X object is value-initialized.

  2. The set of initializations performed by X() = default; is equivalent to that of X() {}, which default-initializes m_y. X() : m_y() {} value-initializes m_y. Depending on what Y is, this can be different. For example, if Y is int, then default-initialization will leave it with an indeterminate value, while value-initialization will set it to zero.

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

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