Global variables in modern C++

↘锁芯ラ 提交于 2019-12-01 10:48:56

Is it "good practice" to create a class where all members (attributes, functions) are static?

This is called "monostate" and it depends.

Or would you rather create a namespace?

A class with static functions can be a template argument, whereas a namespace cannot. On the other hand, namespaces allow for argument-dependent lookup, whereas classes - less so.

Or would you rather create global variables/functions?

Some things are truly global, like the standard streams, Logger objects, event loop engines (thread-specific global). For example, code that passes Logger objects in each and every call or stores them as member variables is more complicated than necessary, IMO.

There is an often cited misconception that the order of dynamic initialization accross translation units is undefined, so people overuse Singletons instead of plain globals to make sure the Singleton object is initialized before its first use. However, there is a portable technique called Schwarz Counter that is used for initializing the standard streams (std::cout and friends), which makes sure that these globals are initialized before their first use even before main is entered.


Answers to your updated questions: no, no, no.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!