Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any advantages to making a free static function?

Tags:

c++

I have a .cpp file which has some static free functions. I know how that would help in a header file, but since the cpp is not included anywhere, what's the point? Are there any advantages to it?

like image 409
Luchian Grigore Avatar asked Sep 30 '11 12:09

Luchian Grigore


People also ask

What is the advantage of static function?

Declaring a function as static prevents other files from accessing it. In other words, it is only visible to the file it was declared in; a "local" function. You could also relate static (function declaration keyword, not variable) in C as private in object-oriented languages.

When should you use static functions?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.

Should all functions be static?

Absolutely yes. The non-static member functions are meant to cater the non-static member variables. If variables are not used then the function should be made static which makes your design cleaner and you can avoid passing this as the 1st hidden argument (which betters the performance a little).


1 Answers

Declaring free functions as static gives them internal linkage, which allows the compiler more aggressive optimizations, as it is now guaranteed that nobody outside the TU can see that function. For example, the function might disappear entirely from the assembly and get inlined everywhere, as there is no need to provide a linkable version.

Note of course that this also changes the semantics slightly, since you are allowed to have different static functions of the same name in different TUs, while having multiple definitions of non-static functions is an error.

like image 54
Kerrek SB Avatar answered Sep 23 '22 13:09

Kerrek SB