Search code examples
c++constructordefaulted-functions

Are user-defined default constructors less efficient?


Some days ago, while reading Standard C++ news I've read the post about Defaulted functions in C++11, in that article is mentioned that the user-defined constructor is less efficient than the one generated by the compiler:

The user-defined default constructor is less efficient than the compiler implicitly defined default constructor.

Continuing the reading, there's an example where an user-defined constructor is marked as default, and then says:

the explicitly defaulted constructor is more efficient than a manually programmed default constructor.

I don't understand these assertions, so I was wondering:

  • Why a user-default constructor (or special member function) would be less efficient than the compiler implicitly defined one?
  • How is the efficiency improved by explicitly defaulting a constructor (or special member function)?
  • What guidelines I must follow to choose to default a constructor (or special member function) and how the efficiency affects this decision?

Solution

  • I think a better statement is that a user-defined default constructor MAY be less efficient than a compiler generated out.

    For example, when it's generating a default constructor internally the compiler may be able to make assumptions and optimizations that it can't make for a user-defined contstructor (side-effects come to mind).

    Also keep in mind that a user-defined default constructor could do totally different work that default-constructing all its members, resulting in it being less efficient (but also more correct). This doesn't seem to be the case in the link you provided however.