Reputation: 659
I know that we should declare a function as static in a class if its a utility function or if we have to use in a singleton class to access private static member.
But apart from that does a static function provide any sort of compiler optimization too since it doesn't pass the "this" pointer? Why not just use the utility function through an already instantiated object of class? Or is it just a best practice to make utility functions as statics?
Thanks in advance.
Upvotes: 1
Views: 2182
Reputation: 12700
The "non-passing-this" optimization can probably be done by the compiler once you turn the optimizations on. As I see it, a static function has rather idiomatic uses:
this
and have the compiler to enforce it. It makes sense sometimes. For example, if you have a commutative operation that takes two instances, a static function that takes the two instances would emphasize (in my opinion) that the operation is commutative. Of course in many cases you would rather overload an operator.In general a static function will ease namespace and "friend" clutter by prefixing an otherwise ordinary function with the name of a class, presumably because both are tightly related.
Upvotes: 1
Reputation: 4109
Static exists to associate a method with a class, rather than either:
Static says that 'conceptually this is something tied to/associated with this class, but it does not depend on any instance of that class'.
In more formal terms: a static member function is the same as a function declared outside of a class in all ways other than that it is part of that class's namespace and in that it has access rights to that class's private/protected data members.
Going back to your question:
Upvotes: 1