开发者

C++ Singleton Vs static methods [duplicate]

开发者 https://www.devze.com 2023-01-27 13:30 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: C++ singleton vs completely static object
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C++ singleton vs completely static object

Hi,

why should I prefer a singleton over static class methods.

    MoneyPrinter::addJob(PrinterJob &job);
or
    MoneyPrinter::getInstance().addJob(PrinterJob &job);

Is it only a matter of style? What do you use? Why?

ps. I know that sigletons are not 开发者_运维百科threadsafe (first initialization) by default.


why should I prefer a singleton over static class methods

A singleton can have internal state (in your example, the list of added jobs), i.e. the member data of the singleton class.

What do you use? Why?

If there's no state, then a static method because that's simplest.

Otherwise a singleton, preferably static-initialized (instead of just-in-time or run-time initialized).


A singleton gives you control over when the class is instantiated and as DeadMG points out if you want to instantiate it. A static class is less controllable and is instantiated before main is called.

The sequence in which classes is instantiated can sometimes be critical when the singleton depends on some other class or resource which is not avaiable before main is called.

As you mentioned, if you call a singleton from multiple threads you need to ensure that you have used a thread safe singleton. Scott Meyer's (from Effective C++) is not thread safe for example.


Would be harder to refactor out the Singleton-ness simply because of the syntax used if you use static member functions. There's one reason.


The general rule of singletons is, if you have to ask, don't use it. This is true for any globally mutable state.

0

精彩评论

暂无评论...
验证码 换一张
取 消