开发者

How can I do some code work just like a singleton? [duplicate]

开发者 https://www.devze.com 2023-02-07 04:19 出处:网络
This question already has answers here: Closed 12 years ago. Possible Dupl开发者_开发问答icate: C++ Singleton design pattern.
This question already has answers here: Closed 12 years ago.

Possible Dupl开发者_开发问答icate:

C++ Singleton design pattern.

How can I create only one instance of a class and share that instance with all my header and source files without using a singleton? Can you provide a simple example?


You can do this:

class Sample
{
   /*** your code **/
   public:
    Sample();
    void DoWork();
    int  GetValue();
  /*** other functions ***/
};

Sample & OneInstance()
{
    static Sample instance;
    return instance;
}

//Use OneInstance everywhere like this
OneInstance().DoWork();

Note Sample is not a Singleton, but you can use OneInstance() function as if it's one and the same instance of Sample, which you use everywhere!

You can use it to initialize some global variables also like this:

int g_SomeValue= OneInstance().GetValue();

which cannot be done with global static instance of Sample. That is because of this:

static initialization order fiasco


Don't do.


I'd advice against sharing anything whenever you can avoid it, because sharing makes concurrency hard. If you don't care about concurrency then you should pass your object around as an extra parameter to functions. Globals are usually a bad idea and Singletons are usually mere globals with a fancy dress.

0

精彩评论

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