Reputation: 4719
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;
};
Upvotes: 3
Views: 170
Reputation: 137394
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 an X
object is value-initialized.
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.
Upvotes: 7
Reputation: 658
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
Upvotes: 0