C++ Templates: Convincing self against code bloat

前端 未结 7 1070
暖寄归人
暖寄归人 2020-12-09 18:08

I have heard about code bloats in context of C++ templates. I know that is not the case with modern C++ compilers. But, I want to construct an example and convince myself.

7条回答
  •  情书的邮戳
    2020-12-09 18:53

    In this specific case, you'll find that g++ will tend to inline the accessor if you have any sort of optimization on. That right there is some minor code bloat, though it's debatable if the overhead of the call would be any less.

    However, one easy way to verify what's getting compiled is with the nm tool. If I compile your code with a simple main() to exercise ArrayX::data() and ArrayY::data() and then compile it with -O0 to turn off inlining, I can run nm -C to see the symbols in the executable:

    % nm -C test
    0804a040 B ArrayX
    0804a1e0 B ArrayY
    08049f08 d _DYNAMIC
    08049ff4 d _GLOBAL_OFFSET_TABLE_
    0804858c R _IO_stdin_used
             w _Jv_RegisterClasses
    080484c4 W Array::data()
    08049ef8 d __CTOR_END__
    08049ef4 d __CTOR_LIST__
    08049f00 D __DTOR_END__
    ...
    

    You'll see that the Array::data() symbol only occurs once in the final executable even though the object file for each of the two translation units contains it's own copy. (The nm tool also works on object files. You can use it to check that x.o and y.o each has a copy of Array::data().)

    If nm doesn't provide enough detail, you might also have a look at the objdump tool. It's a lot like nm, but with debugging symbols turned on, it can even show you things like a disassembly of the output executable with intermixed source lines.

提交回复
热议问题