C++, static vs. namespace vs. singleton

后端 未结 6 1599
孤城傲影
孤城傲影 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:13

    Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.

    You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.

    If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

提交回复
热议问题