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?
Making a function a static member of a class rather than a free function gives two advantages: It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function; It associates the function with the class in a similar way to a namespace.
1.1 Unnamed namespaces, paragraph 2: The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
Unnamed namespaces are typically used when you have a lot of content that you want to ensure stays local to a given file, as it's easier to cluster such content in an unnamed namespace than individually mark all declarations as static .
A namespace with no identifier before an opening brace produces an unnamed namespace. Each translation unit may contain its own unique unnamed namespace. The following example demonstrates how unnamed namespaces are useful.
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.
I started doing this several years ago and never found any real draw backs. Anything that the object uses, but doesn't itself change the state of the object and doesn't need to be used anywhere else, I like to put in an anonymous namespace in the implementation file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With