C++, static vs. namespace vs. singleton

As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn’t happen THAT often).

Stashing everything in a class is something you would do in a Java-like language, but in C++ you don’t have to, and in fact using namespaces here is a superior alternative, if only:

  • because people won’t suddenly build instances of your objects: to what end ?
  • because no introspection information (RTTI) is generated for namespaces

Here is a typical implementation:

// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED

namespace myproject {
  void foo();
  void foomore();
}

#endif // MYPROJECT_FOO_H_INCLUDED

// foo.cpp
#include "myproject/foo.h"

namespace myproject {

namespace {
  typedef XXXX MyHelperType;

  void bar(MyHelperType& helper);
} // anonymous

void foo() {
  MyHelperType helper = /**/;
  bar(helper);
}

void foomore() {
  MyHelperType helper = /**/;
  bar(helper);
  bar(helper);
}
} // myproject

The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what’s inside, but he does not even see it at all (since it’s in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)

Leave a Comment

tech