3

When writing C++ code within the CLion IDE one of the Clang-Tidy messages that comes up is this function can be made static. Is there any benefit (mainly performance?) for making this function static, if it won't be used outside the class and thus, removes one of the main uses of static functions.

Danke

Adriano
  • 80
  • 11
  • No `this` pointer will be passed to a `static` function, so technically you save performance – UnholySheep Dec 08 '21 at 20:15
  • 3
    Essentially if your class method does not require state (in other words does not require `this` nor does it access/mutate any data members) then the function should either be `static` or often a free-function within a `namespace` – Cory Kramer Dec 08 '21 at 20:17
  • @CoryKramer I understand that the function _could_ be made static, but my main curiosity is there any benefit to making it static? Just for the explicitness to state that this member function does not require any member variables? – Adriano Dec 08 '21 at 20:20
  • @AlexGuteniev you're right. I didn't catch "member" in the title. – Drew Dormann Dec 08 '21 at 20:21
  • Potentially lower cognitive load. It's now obvious to the casual reader that the method has no direct effect on object state. Could also prevent unintended side effects by making a mistake turn into a compiler error. – user4581301 Dec 08 '21 at 20:22
  • It expresses intent. If the IDE is suggesting that a method could be `static` that should give you pause to reflect on why that function is a member of the class in the first place. – Cory Kramer Dec 08 '21 at 20:25
  • 2
    Put the question the other way around: should I define a function so that it takes arguments that it won't use? – Pete Becker Dec 08 '21 at 20:35
  • @PeteBecker The function will use all the arguments it is provided? It's more, the member variables will not be used. In order to make the code a little easier to read, I tend to create helper functions which sometimes will not use the member variables of the function but simplifies the code for the programmer – Adriano Dec 08 '21 at 20:46
  • @CoryKramer As stated in the comment above, it's mainly for helper functions to break up a larger function to make it more readable and easier to parse. It doesn't make sense to me to create an additional set of files for auxiliary functions for a single use case in a class, hence helper functions in the class. – Adriano Dec 08 '21 at 20:47
  • 1
    It is a matter of preference, don't sweat over it. – SergeyA Dec 08 '21 at 22:28

0 Answers0