Singleton实例声明为GetInstance方法的静态变量 [英] Singleton instance declared as static variable of GetInstance method
问题描述
我见过Singleton模式的实现,其中实例变量在GetInstance方法中被声明为静态变量。像这样:
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:
SomeBaseClass &SomeClass::GetInstance()
{
static SomeClass instance;
return instance;
}
我看到以下积极的方法:
I see following positive sides of this approach:
- 代码更简单,因为编译器只有在第一次调用GetInstance时才负责创建此对象。
- 代码更安全,因为没有其他方法可以引用实例,但是使用GetInstance方法,没有其他方法来更改实例,但是在GetInstance方法内。
这种方法的负面是什么(除了这不是很OOP-ish)?
What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?
推荐答案
在C ++ 11中,它是线程安全的:
In C++11 it is thread safe:
§6.7[stmt.dcl] p4如果控制在变量初始化时并发执行声明,并发执行将等待初始化完成。
§6.7 [stmt.dcl] p4 If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
在C ++ 03中:
- 线程安全。
但是这是因为g ++明确添加了代码来保证它。
你有两个单身,他们在建造和破坏期间尝试和使用彼此。
One problem is that if you have two singletons and they try and use each other during construction and destruction.
阅读:
查找C ++静态初始化顺序问题
是如果从全局变量的析构函数访问单例。在这种情况下,singleton已经被销毁了,但是get方法仍然会返回对被销毁的对象的引用。
A variation on this problem is if the singleton is accessed from the destructor of a global variable. In this situation the singleton has definitely been destroyed, but the get method will still return a reference to the destroyed object.
这里有一些方法,值得做。只要不要从全局变量的析构函数中访问单例。
There are ways around this but they are messy and not worth doing. Just don't access a singleton from the destructor of a global variable.
一个更安全的定义,但是很丑陋:
我相信你可以添加一些合适的宏整理这个
A Safer definition but ugly:
I am sure you can add some appropriate macros to tidy this up
SomeBaseClass &SomeClass::GetInstance()
{
#ifdef _WIN32
Start Critical Section Here
#elif defined(__GNUC__) && (__GNUC__ > 3)
// You are OK
#else
#error Add Critical Section for your platform
#endif
static SomeClass instance;
#ifdef _WIN32
END Critical Section Here
#endif
return instance;
}
这篇关于Singleton实例声明为GetInstance方法的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!