单例的静态变量位置
我有一个关于singlton的问题。
我应该在哪里声明单例类的静态成员?
为什么不这样工作
class singleton{
private:
static singleton & m_singleton;
public:
static singleton& get_instance{
return m_singleton;
}
}
但我必须这样有
class singleton{
public:
static singleton& get_instance{
static singleton & m_singleton;
return m_singleton;
}
}
什么区别?
我知道还有另一种使用指针的方法,但现在我只讨论使用对象的情况。
还有另一个问题,使用指针和引用作为单例有什么优点/缺点?
非常感谢!
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/cons to use pointer and reference for singleton ?
Thanks so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第一种情况下,单例是在程序初始化时、调用
main()
之前构造的(调用构造函数)。在这种情况下,您还需要在 cpp 文件中的某个位置定义静态变量。在第二种情况下,单例是在第一次调用函数时构造的。请注意,此实现不是线程安全的,因为函数中的静态变量初始化不是线程安全的。如果两个线程似乎是第一次调用此函数,则很有可能最终会得到两个单例。
另请注意,第二个中有一个错误。如果没有初始化,则无法定义引用。这
不会编译。您需要删除引用以创建该类的实际实例(而不是引用),然后返回对其的引用。
如果在第二个示例中将静态变量定义为指针,则可以通过仔细初始化指针来避免我提到的线程问题。在此类文章中阅读有关它的更多信息(该文章讨论了 Java,但核心问题是一样的)
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
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)