Why are inline constructors and destructors not a good idea in C++?

后端 未结 5 1990
夕颜
夕颜 2021-02-01 21:20

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 understa

相关标签:
5条回答
  • 2021-02-01 21:52

    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.

    0 讨论(0)
  • 2021-02-01 21:54

    There's absolutely no reason whatsoever to avoid inline constructors and destructors. The book is wrong as wrong can be.

    0 讨论(0)
  • 2021-02-01 21:55

    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.

    0 讨论(0)
  • 2021-02-01 22:03

    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.

    0 讨论(0)
  • 2021-02-01 22:04

    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.

    0 讨论(0)
提交回复
热议问题