C++, static vs. namespace vs. singleton

后端 未结 6 1590
孤城傲影
孤城傲影 2020-12-01 07:34

I already read a lot of posts and articles all over the net, but I couldn\'t find a definite answer about this.

I have some functions with similar purposes that I wa

6条回答
  •  一生所求
    2020-12-01 08:22

    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!)

提交回复
热议问题