显式默认的构造函数和成员变量的初始化 [英] Explicitly defaulted constructors and initialisation of member variables
问题描述
以下两个代码示例是否相同?
$ b $ b
Y
是否有任何约束可以使用第一个选项?
class X
{
public:
X()= default;
private:
Y m_y;
};
class X
{
public:
X():m_y(){}
private:
Y m_y ;
};
有两种可能的差异来源。 >
-
X()= default;
不是用户提供。X():m_y(){}
是。前者可以琐碎;后者从来不是微不足道的。此外,如果X
对象是值初始化的,它们的行为会有所不同。 -
由
X()= default;
执行的操作等效于X(){}
-initializesm_y
。X():m_y(){}
value-initializesm_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.
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 anX
object is value-initialized.The set of initializations performed by
X() = default;
is equivalent to that ofX() {}
, which default-initializesm_y
.X() : m_y() {}
value-initializesm_y
. Depending on whatY
is, this can be different. For example, ifY
isint
, then default-initialization will leave it with an indeterminate value, while value-initialization will set it to zero.
这篇关于显式默认的构造函数和成员变量的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!