Search code examples
c++c++11constructordefaultdefault-constructor

What do explicitly-defaulted constructors do?


Consider the following:

template <class T>
struct myclass
{
    using value_type = T;
    constexpr myclass() = default;
    constexpr myclass(const myclass& other) = default;
    constexpr myclass(const myclass&& other) = default;
    T value;
};
  • To what constructor bodies these function are equivalent?
  • Does myclass<int> x; initialize the integer at 0?
  • For myclass<std::vector<int>> x; what does the default move constructor do? Does it call the move constructor of the vector?

Solution

  • They aren't equivalent to any function bodies. There are small but significant differences between the three cases: = default, allowing implicit generation, and the nearest equivalent function body.

    The following links explain in more detail:

    I couldn't find a good link about copy-constructor; however similar considerations as mentioned in the other two links will apply.


    myclass<int> x; does not set value to 0.

    The defaulted move-constructor (if you made it a non-const reference) moves each movable member (although I think there is a special case where if there is a non-movable base class, weird things happen...)