Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a C++ template use memory if it is never referenced?

Let's say I declare a template but never reference it in C++. Does the compiler do anything with it in the executable? Does it take up any process memory?

like image 358
Iowa15 Avatar asked Jun 25 '13 18:06

Iowa15


2 Answers

No, no code will be produced for a function template which is never instantiated. Also, no code will be produced for a non-template member function of a class template which is never called.

In particular, the size of your executable won't be any bigger, nor will any run-time overhead occur.

like image 165
Andy Prowl Avatar answered Oct 15 '22 15:10

Andy Prowl


No it does not.

Template classes and functions are not actual classes or functions: They are instead directions to the compiler for how to generate certain types of classes and functions. When you reference a template, the compiler, uses the template in order to figure out how to generate the source code, and compiles the generated code, once for each different parameterization of the template.

The only overhead to using a template is a little extra compile time, no big deal for any computer built anytime after the 1980s.

like image 26
AJMansfield Avatar answered Oct 15 '22 15:10

AJMansfield