3

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;
};
T.C.
  • 133,968
  • 17
  • 288
  • 421
ksl
  • 4,519
  • 11
  • 65
  • 106

2 Answers2

7

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.

T.C.
  • 133,968
  • 17
  • 288
  • 421
0

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

  • Some details must rely on implementation, like zero initialization of ints... but strictly speaking, the default is just the same as the other two constructors. Nevertheless, I think that introducing default is required in order to let the compiler to choose when generate it. If default dont exists, the compiler gets forced to generate the constructor even when is not used. That's imho the key. – Mel Viso Martinez Apr 15 '15 at 16:44