Will the compiler exclude unused template code?

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

+6
source share
4 answers

A template is not created if it is not used, so there is actually no code to drop.

The standard says (14.7.1 / 10)

An implementation should not implicitly create a function template, a member template, a non-virtual member function, a member class, or a static data element of a class template that does not require instantiation. It is unclear whether the implementation implicitly implements an instance of a virtual member function of a class template if the virtual member function were not otherwise implemented. Using template specialization in a default argument should not result in a template being implicitly created, except that a template template can be created when its full type is needed to determine whether the default argument is valid. Using the default argument in a function call causes specializations in the default argument to be implicitly created.

So, if you can avoid the virtual functions of a template member, the compiler will not generate any code for them (and this can work for virtual functions if the compiler is smart enough).

+6
source

It depends on your level of optimization. With higher optimization settings, yes, most likely, dead code will be deleted.

+4
source

the compiler, optimizers and linker can omit and / or reduce this information. every mature tool probably has options specific to eliminating dead code.

with templates, the code cannot actually be created in the first place (except for the instance).

Of course, not all of this will be removed in each scenario, however (rtti is a silent killer). a little caution and testing using build settings can greatly help you reduce the size of binary files and dead code.

+1
source

Smart compilers will most likely rule it out. Once upon a time, when I was playing with Borland C ++ Builder, I think it did not throw away unused template class methods. Failed to confirm though

0
source

Source: https://habr.com/ru/post/922503/


All Articles