C++ singleton vs. global static object(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.
这篇关于C++ 单例 vs. 全局静态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 单例 vs. 全局静态对象
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
