开发者

static variable position of singleton

开发者 https://www.devze.com 2023-02-22 21:15 出处:网络
I have a question with singlton. Where should I declare the static member of the singleton class? why not working like this

I have a question with singlton.

Where should I declare the static member of the singleton class?

why not working like this

class singleton{

  private:

  static singleton & m_singleton;

  public:

  static singleton& get_instance{

          return m_singleton;
  }

}

but I have to be like this

class singleton{

  public:

  static singleton& get_instance{

     static singleton & m_singleton;

          return m_singleton;
  }

}

What's the differnece?

I know there is another way to use pointer, but now I am only talking about the case to use an object.

Also another questions, what's the pros/c开发者_如何学运维ons to use pointer and reference for singleton ?

Thanks so much!


In the first case, the singleton is constructed (constructor called) when the program initializes, before main() is called. In this case you will also need to define the static variable somewhere in your cpp file.

In the second case the singleton is constructed when the function is first called. Mind you that this implementation is not thread safe since static variable initialization in functions is not thread safe. If two threads call this function for what appears to be the first time, there is a small chance you'll end up with two singletons.

Also notice you have a bug in the second one. You cannot define a reference without an initalization. This

static SomeClass &var;

Does not compile. You need to remove the reference to create an actual instance of the class, not a reference, and then return a reference to it.

If in the second example you define the static variable as a pointer you can avoid the threading problem I mentioned by carefully initializing the pointer. Read more about it in this class article (that talks about Java but the core issue is the same)

0

精彩评论

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