Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static free functions or member functions for helpers?

Tags:

c++

Suppose you have the following non-static member function:

// .h
struct C {
    void f();
}

Now suppose you want to implement C::f by using some sub-functions specific to C::f, to make it shorter and more readable; for example:

// .cpp
void C::f() {
    h1();
    h2();
    //...
    hn();
}

suppose that many of those h()'s functions do not need to access any data members. This means that you may well define the functions either as static free functions (in one .cpp) or as member functions (static or not).

Would you make them static free functions or function members of C?

One advantage in the first case is that you will not have to declare them in C:

// .cpp
static void h1() {//...}
static void h2() {//...}
static void hn() {//...}

Also, if I am not wrong, there is no risk of global namespace pollution, since they are static, that is they can only be seen from other functions inside the same unit .cpp (in which C::f is also defined).

while in the second case you will have to declare them in C, although, as I said, they are only supposed to be used by C::f.

// .h
struct C {
    void f();
  private:
    static void h1(); // can be either static or non-static
    static void h2();
    static void hn();
}

// .cpp
void C::h1() {//...}
void C::h2() {//...}
void C::hn() {//...}

I think the second version results in bloated code for no good reason, above all if you end up having to split other long member functions like C::f to make the code more readable.

like image 861
Martin Avatar asked Oct 06 '22 18:10

Martin


1 Answers

I would suggest using an anonymous namespace:

namespace {
    void C::h1() {/...}
    void C::h2() {/...}
    void C::h3() {/...}
}

(see this question)

That way, you guarantee that the function is not visible outside the file it is defined and thus you are in no way polluting your global namespace - which would be my main concern for free static functions.

Making them private members of your class exposes the function interface to the whole world (as you publish your *.h file) and thus just makes the interface more complicated for no reason. (There are more arguments you could add here, for example higher compilation times when changing the definition of a private function)

Searching for "anonymous namespaces" results some interesting discussions on this topic.

like image 96
Thilo Avatar answered Oct 10 '22 01:10

Thilo