c++functionnamespacesstatic-membersunnamed-namespace

Should I use a private static member function, or free function in an unnamed namespace?


I've recently made a change stylistically and wanted to see how other c++ programmers felt about it and if there were any downsides to it.

Essentially, when I needed a utility function which doesn't need access to a given class member, what I used to do was something like this:

file.h

class A {
public:
    // public interface
private:
    static int some_function(int);
};

file.cpp

int A::some_function(int) {
    // ...
}

But more recently, I have been preferring to do something more like this:

file.cpp

namespace {
    int some_function(int) {

    }
}
// the rest of file.cpp

Here's my thought process:

The last one is the most compelling to me. So my question is: are there any downsides to this?

They are functionally equivalent for most purposes that I can think of. It kind of seems to me that a private static function can almost always be converted to a free function in an anonymous namespace.

EDIT: One thing that comes to mind is that a private static function would have access to private members if given a pointer to an object to operate on, but if that's the case, why not make it a non-static member?

What do you guys think?


Solution

  • If the function is only used in one source file, it makes perfect sense to define it there. If nobody else is using it, it doesn't belong in the header.

    As you say, it reduces dependencies and can potentially save some recompiles.