开发者

[C++]function template with static keyword

开发者 https://www.devze.com 2023-01-28 14:23 出处:网络
code from google\'s 开发者_运维技巧v8 js engine, allocation.h: template <typename T> static void DeleteArray(T* array) {

code from google's 开发者_运维技巧v8 js engine, allocation.h:

 template <typename T>
 static void DeleteArray(T* array) {
  delete[] array;
}

This is a function template (top level, not in any class). But what the static keyword is for?


That it's a template is actually a side-issue.

It being static means the function is not visible outside of the file (but since it's in a header and headers are effectively part of the files that include them, that means outside of the file that includes the header; and each file that includes the header effectively has its own, identical but private version of the function).

From http://msdn.microsoft.com/en-us/library/s1sb61xd%28VS.80%29.aspx:

"When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared)."

See here fore more on what it means to have this in a header file:

C/C++: Static function in header file, what does it mean?


The static keyword gives the definition "internal linkage", which means it would be legal to give the name DeleteArray another meaning or a different definition in a different source file. (Just as is the case with static void f(); or static int i;.) But I can't imagine anyone would want to do that.

Use of static this way in C++ is deprecated. This declaration would probably be better without the static keyword, making it implicitly extern (and still inline). In that case, the linker would be allowed to combine any definitions of DeleteArray<T>(T*) for the same T from multiple objects, since they would be the same thing.


static functions (outside of a class) cannot be used outside the defining file. It's a holdover from C where there are no namespaces. I bet you'll find that DeleteArray() isn't called from another file, unless it's been redefined in that other file.

0

精彩评论

暂无评论...
验证码 换一张
取 消