I read this article from D. Kalev this morning about the new c++11 feature "defaulted and deleted functions", and can't understand the part about performance, namely:
the manual definition of a special member function (even if it's trivial) is usually less efficient than an implicitly-defined one.
By googling to find an answer, I found another article of the same author:
the synthesized constructor and copy constructor enable the implementation to create code that's more efficient than user-written code, because it can apply optimizations that aren't always possible otherwise.
There is no explication, but I read time to time similar claims.
But how is it that writing:
class C { C() = default; };
can be more efficient than
class C { C(){} };
? I though a compiler would be smart enough to detect such situation and optimize that. In other words how is it easier for the compiler to optimize when it sees =default
instead of {}
(void body function)?
Edit: the question was edited to add the "c++11" tag, but this question remains in c++03 context: just replace class C {C()=default;};
by class C {};
, so not really a c++11 specific question.
The copy constructor is used only for initializations, and does not apply to assignments where the assignment operator is used instead. The implicit copy constructor of a class calls base copy constructors and copies its members by means appropriate to their type. If it is a class type, the copy constructor is called.
implicit constructor is a term commonly used to talk about two different concepts in the language, the. implicitly declared constructor which is a default or copy constructor that will be declared for all user classes if no user defined constructor is provided (default) or no copy constructor is provided (copy).
If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.
A trivial default constructor is a constructor that performs no action. All data types compatible with the C language (POD types) are trivially default-constructible.
You ask, how is it that
class C { C() = default; };
can be more efficient than
class C { C(){} };
Well, both constructors do nothing, so it's meaningless to talk about efficiency for that example.
But more generally, in e.g. a copy constructor one can imagine that copying one POD item at a time will not be recognized as optimizable by simple optimizer, whereas with automatic generation it might just do a memcpy
. Who knows. It's a Quality of Implementation issue, and I can easily imagine also the opposite.
So, measure, if it matters.
Cheers & hth.,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With