0

From the answer of this question I came across a rather interesting phenomenon. Given the following two functions:

void require(void * volatile) { }

template <typename T>
void requireT(T * volatile) { }

Calling each with a pointer to a static data member will enforce that member to be instantiated (which was the purpose of the other question), however, requireT will be optimized away completely, while require has an impact on the resulting code/binary (g++ 4.9.2).

Why is this? What difference is there in how the compiler treats the code?

Community
  • 1
  • 1
zennehoy
  • 6,405
  • 28
  • 55
  • What is the "impact"? Note that the non-template one is not inline, whereas the template is implicitly inline. – Potatoswatter Jan 24 '15 at 07:36
  • @Potatoswatter The template function being implicitly inline was the key. Do you want to convert your comment to an answer? Thanks! – zennehoy Jan 26 '15 at 08:45

2 Answers2

0

Code for templates is generated where it is needed because it is not feasible to generate it before hand for every possible type that might be used. There for when the call to a template function is optimized away the compiler has no reason to generate the function it self.

Normal function are almost always generated even if all calls to them are optimized away because they might also get called from a different compilation unit. Making the function local to the compilation unit by putting static before or putting it in an unnamed namespace might help the compiler to optimize the function completely away.

Eelke
  • 20,897
  • 4
  • 50
  • 76
0

The template is implicitly inline, but the other function is not.

The linker might assume that an unused inline function doesn't need to be included in the compiled binary file because it any client code will always be able to find it in the header file. (Usually, though, all unused functions are stripped when generating an executable application binary.)

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421