I remember reading in one of the C++ books (quite some time ago) that it is not a good idea to have inline Constructors and Destructors especially for derived class. I understand that inlining would induce some bloating up of object code but are there any other design considerations that discourage inline constructors and destructors? Of course most compilers may reject the inline and proceed with creating a function body but if they were to inline what penalty might one have to pay?
问题:
回答1:
The compiler is free to inline code that you have not declared inline, and is free not to inline code that you have declared inline. I have seen compilers do both of these things. Because of this the inline keyword does not mean what most people think it does. It's meaning is to allow an exception to the one definition rule, so you can put functions etc. in a header file and not get linker errors.
So the advice is rubbish, let the compiler decide what is best to inline and what is not. Put inline where you need it to prevent linker errors, that is all.
回答2:
Apart from the reason @oli mentions in his answer:
The book probably guides on not inlining constructors and destructors, because even seemingly trivial or empty functions might often contain lot of implicitly generated code by the compiler and the actual function definition might end up being quite large, This might result in code bloat.
Having said so, It is prudent to let the compiler actually decide whether to inline or not inline a function call (even constructors and destructors), most of modern day compilers will appropriately optimize functions through in-lining.
回答3:
There's absolutely no reason whatsoever to avoid inline constructors and destructors. The book is wrong as wrong can be.
回答4:
I don't know about constructors, but destructors are very often virtual
. In most cases, it doesn't make sense for the compiler to inline virtual functions, because it's not known until runtime which override is going to be called.
回答5:
I'm pretty sure this is not about what C++ does with the code, because, as said, it's just a hint.
If you start looking at software engineering consideration things change. All inline function changes will force recompilations of all dependent files.
It get worse when you maintain a library and want to send out a bug fix version, remaining ABI compatible. Inline functions can simply not be replaced by another version because the calling code may not be recompiled. So where your non-inline function can be replaced at will, you have to move to a new version of your interface when inline functions ned to be changed.
Combine this with the fact that constructors can seldom be actually inlined by the compiler, then you I can imagine why a book would give the advice mentioned.