Question

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?
Was it helpful?

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.

OTHER TIPS

And we all know, that if it's written on internet then it is must be right... Wait, do we?

In the article where I found the first assertion of less efficient, the author tells the truth. Though you seem to misinterpret it -- in the example it refers to the hand-crafted ctor uses assignment. For no good reasons, and going against 2 decade old guidelines.

Next instance, same case. (As a practical note I shall add, that for any compiler claiming to have optimizations I expect the same assy output even for that form...)

I see no reason why the proper handwritten ctor would be different from the defaulted one in any ways, including efficiency. OTOH if they are identical why on earth write it? I'm all too happy that compiler makes it for me. And finally I can even control it in some ways I previously could not. Could use more of such functions. ;-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top