Static variable inside template function

前端 未结 7 1934
一向
一向 2020-12-14 07:10

In C++, if you define this function in header.hpp

void incAndShow()
{
  static int myStaticVar = 0;
  std::cout << ++myStaticVar << \" \" <<         


        
7条回答
  •  悲&欢浪女
    2020-12-14 07:34

    The difference when you create the function template is that it has external linkage. The same incAndShow will be accessible from all translation units.

    Paraphrasing from C++ standard working draft N2798 (2008-10-04): 14 part 4: a non member function template can have internal linkage, others always have external linkage. 14.8 point 2: every specialization will have its own copy of the static variable.

    Your function template should have external linkage unless you declare it in the unnamed namespace or something. So, for each T that you use with your function template, you should get one static variable used throughput the program. In other words, it's OK to rely on having only one static variable in the program for each instantiation of the template (one for T==int, one for T==short, etc).

    As an aside, this can lead to weird situations if you define incAndShow differently in different translation units. E.g., if you define it to increment in one file and the decrement in another file (without specifying internal linkage by putting the function into the unnamed namespace) both will end up sharing the same function, which will effectively be chosen at random at compile time (with g++ it depends on the order the object files are given on the command line).

提交回复
热议问题