Will the compiler exclude unused template code?

我的未来我决定 提交于 2021-02-08 14:00:27

问题


When you use a template with numerous methods (like vector) and compile your code, will the compiler discard the code from the unused methods?


回答1:


A template is not instantiated unless it is used, so there is actually no code to discard.

The standard says (14.7.1/10)

An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation. It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated. The use of a template specialization in a default argument shall not cause the template to be implicitly instantiated except that a class template may be instantiated where its complete type is needed to determine the correctness of the default argument. The use of a default argument in a function call causes specializations in the default argument to be implicitly instantiated.

So if you can avoid making the template's member functions virtual, the compiler will not generate any code for them (and that might work for virtual functions as well, if the compiler is smart enough).




回答2:


It depends on your optimization level. At higher optimization settings, yes, dead code elimination will most likely occur.




回答3:


the compiler, optimizers, and the linker can omit and/or reduce that information. each mature tool likely has options specific to dead code elimination.

with templates, the code may not really be created in the first place (unless instantiated).

certainly not all of it will be removed in every scenario, however (rtti is a silent killer). a bit of caution and testing using your build settings can go a long way to help you reduce the binary sizes and dead code.




回答4:


Smart compilers will exclude it most likely. Long time ago when I played with Borland C++ Builder, I think, it did not throw out unused template class methods. Can not confirm though



来源:https://stackoverflow.com/questions/11890996/will-the-compiler-exclude-unused-template-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!