Chapter 3.2

I.3: Avoid singletons

Global objects are bad

Global objects are bad, m’kay? You will hear this all the time, from programmers young and old, recited as an article of faith. Let’s look into why this is.

A global object lives in the global namespace. There is only one of these, hence the name “global.” The global namespace is the outermost declarative region of a translation unit. A name with global namespace scope is said to be a global name. Any object with a global name is a global object.

A global object is not necessarily visible to every translation unit of a program; the one-definition rule means that it can only be defined in one translation unit. However, a declaration can be repeated in any number of translation units.

Get Beautiful C++: 30 Core Guidelines for Writing Clean, Safe, and Fast Code now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.