C++ 单例 vs. 全局静态对象
今天我的一个朋友问我为什么他更喜欢使用单例而不是全局静态对象?我开始解释的方式是,单例可以有状态,而静态全局对象不会……但后来我不确定……因为这是在 C++ 中……(我来自 C#)
A friend of mine today asked me why should he prefer use of singleton over global static object? The way I started it to explain was that the singleton can have state vs. static global object won't...but then I wasn't sure..because this in C++.. (I was coming from C#)
两者相比有什么优势?(在 C++ 中)
What are the advantages one over the other? (in C++)
推荐答案
实际上,在 C++ 中首选的方式是本地静态对象.
Actually, in C++ preferred way is local static object.
Printer & thePrinter() {
static Printer printer;
return printer;
}
虽然这在技术上是一个单例,但这个函数甚至可以是一个类的静态方法.因此,与全局静态对象不同,它保证在使用前先构造,可以按任何顺序创建,这使得当一个全局对象使用另一个全局对象时可能会不一致地失败,这是一种很常见的情况.
This is technically a singleton though, this function can even be a static method of a class. So it guaranties to be constructed before used unlike with global static objects, that can be created in any order, making it possible to fail unconsistently when one global object uses another, quite a common scenario.
通过调用new
来创建新实例比普通的单例方法更好的是对象析构函数将在程序结束时调用.动态分配的单例不会发生这种情况.
What makes it better than common way of doing singletons with creating new instance by calling new
is that object destructor will be called at the end of a program. It won't happen with dynamically allocated singleton.
另一个积极的方面是,即使从其他静态方法或子类,也无法在创建之前访问单例.为您节省一些调试时间.
Another positive side is there's no way to access singleton before it gets created, even from other static methods or from subclasses. Saves you some debugging time.
相关文章