1

Not asking how one should use singletons here, nor advocating singletons or globals. With that clarified:

If we assume someone wants a global + unique object, why isn't a namespace always the preferred approach in C++, over implementing a singleton class?

I've only seen the namespace approach encouraged when there aren't statics being shared. Eg; from Google's style guidelines:

"Rather than creating classes only to group static member functions which do not share static data, use namespaces instead."

But why not have non-member functions that share static data, declared in an unnamed namespace? And why isn't this generally suggested as a better alternative to writing a singleton class in C++?

Xenial
  • 465
  • 2
  • 15
  • 1
    Singleton is a design pattern. Design patterns might be overrated. As you say, if you only need one object just create a single object and be done with it. – Bo Persson Oct 20 '17 at 12:51
  • As a communication tool for developers, design patterns per se are certainly not overrated. The singleton pattern as a specific design pattern is probably not as useful in todays software development landscape as it might have been in the past. – anothernode Oct 20 '17 at 12:54
  • I think this has been wrongly marked as a duplicate. I've edited the question to clarify that I'm not asking how to use a singleton. – Xenial Oct 20 '17 at 13:12

0 Answers0