Re: inline constructor and destructor
On Sep 12, 7:21 pm, Tim <Tian.Xiao.2...@gmail.com> wrote:
I am confused about when I should use inline constructors and
destructors. I have test some simple cases, seems the inline ones are
faster. Why some book suggest not use/overuse the inline constructors
and destructors?
The simple answer is that you should never inline, or only when
the profiler shows that you must. Inlining significantly
increases coupling, and should be avoided unless absolutely
necessary.
A more complex answer would take into account cases where the
coupling is present anyway, e.g. templates (in the lamentable
absense of export), and "local" classes, only used in the
implementation of some exported class. There are also some
cases where it may be desirable to use inline in order to
completely avoid having a source file/object file---I generally
inline the virtual destructor of an interface, as 1) by
definition, it will be empty, and never change, and 2) it seems
a real waste to require a .cc file and to generate an object
file for a single, empty function.
Also, some modern compilers (not many, yet) are better at
deciding what to inline than you are, and many are quite capable
of inlining code which hasn't been declared inline, even if the
function definition isn't in the same compilation unit. Long
term, I would expect this to be the general case, since the
decision to inline or not really should depend on the frequency
the call site is executed, not on which function is being
called. (In this regard, the way C handles inline is actually
superior to what C++ does, although it is overly complex and
awkward to use otherwise.)
If a book emphasizes not inlining constructors and destructors,
it is probably because in these cases, even apparently trivial
or empty functions often contain a lot of implicit, compiler
generated code, and can end up quite large, and result in
significant code bloat. (This is probably less of an issue than
it used to be, but it is still worth considering; even if code
bloat typically won't prevent the code from fitting in memory,
it will reduce locality, and increase cache misses, and possibly
even cause more page faults.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34