问题
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;
};
回答1:
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.
回答2:
There are the same. With explicit cto'rs you only enforce his creation. Otherwise, the compiler can avoid create it if you are not using the default constructor. May be interesting when creating shared libraries. For reference http://en.cppreference.com/w/cpp/language/default_constructor
来源:https://stackoverflow.com/questions/29646685/explicitly-defaulted-constructors-and-initialisation-of-member-variables