开发者

penalty for "inlined" classes

开发者 https://www.devze.com 2022-12-26 15:18 出处:网络
Visual studio allow you to create \"inlined\" classes (if I am not mistaken with the name). So class header and implementation all in one file.

Visual studio allow you to create "inlined" classes (if I am not mistaken with the name). So class header and implementation all in one file.

H. file contain definitions and declarations of the class and functions, there is no .cpp file at all.

So I was wondering if there is any penalty for doing it that wa开发者_JS百科y? any disadvantages ?

Thanks a lot


any penalty for doing it that way? any disadvantages?

Yes. If you need to change the implementation of the class, since this is in a header file, all users of the class need to recompile, even though they should only be concerned with the interface. For some projects, this can be quite expensive.


You can put the complete implementation of a class in the header with any compiler. There's usually a penalty in terms of compile time -- the header will be compiled separately for each source file that includes it.

There may be a penalty in terms of code bloat as well -- putting the function definitions inside the class definition implicitly declares them inline, so there may be an increased likelihood of the compiler generating code for each of them individually instead of generating code in one place, and generating calls to it elsewhere.


A pretty bad idea if you ask me, especially for big projects. Take a look at Lakos' "Large-Scale C++ Software Design" to learn more about the drawbacks of such approach.


There's another potential penalty: Performance. If you make too many functions inline, this leads to code bloat, which results in executables which functions and loops may not fit into the instruction cache of the target CPU.


No penalty.
But it also does not mean that the code is actually inlined.

They inline keyword is only a compier hint that is usually ignored as the compiler is usually much smarter than the developer in terms of knowing when to inline code.


The inline keyword is only a hint to the compiler to inline code. Visual Studio has a __forceinline specifier for functions that would make the compiler forcibly inline the function without a cost/benefit analysis.

About __forceinline : http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx

The *.h file having all the definitions and declarations should not make any difference though except for compile times for large files.


There are two "penalties"

  • One will be assessed at compile time. If you have an unusually large project, you'll have lots of header files that the preprocessor will expand into one another with much more code. Changing one .h file will trigger a recompilation in all the files that include it.
  • The other is that it (may possibly) lead to larger binaries because that code is replicated in other object files.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号