tariq zafar
tariq zafar

Reputation: 659

static functions compiler optimization C++

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

Answers (2)

dsign
dsign

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:

  • Implementing modules. There is a bit of overlap here with namespaces, and I would rather use namespaces.
  • Factories: you can make the constructor protected/private and then have several static functions (with different, explicit names) creating instances.
  • For function pointers: static functions do not require the slightly more complicated syntax of pointer to member function. That can be a plus when interacting with libraries written for C.
  • To keep yourself from using 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

Mark
Mark

Reputation: 4109

Static exists to associate a method with a class, rather than either:

  1. Associating it with an instance of that class (like writing a normal, non-static member function).
  2. Keeping it in the global namespace or whatever namespace you would otherwise be in (like declaring a function just in the file, not in a class).

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:

  1. There is no optimization gain here.
  2. Utility function has nothing to do with it. It's whether or not it makes sense to scope the function in the class itself (rather than an instance of it).
  3. It does not 'pass the this pointer' because there is no instance to speak of. You can call a static member function without ever invoking that class's constructor.

Upvotes: 1

Related Questions