从BOOST或c++ 14类中删除其他单例类中的ACE_Singleton
Removal of ACE_Singleton with some other Singleton class from BOOST or C++14 class
我们正在从C++03
迁移到C++14
,这是从ACE库开始的决定。我们主要将ACE库用于单例对象和锁。因此,对于锁,我们可以使用C++11/14
中的mutex
,但是ACE_SINGLETON的更好替代品是什么呢?
#include <iostream>
class foo;
foo& get_foo();
class foo
{
friend foo& get_foo();;
private:
~foo () { std::cout << "foo destroyed" << std::endl; }
foo () { std::cout << "foo constructed" << std::endl; }
foo(const foo&) = delete;
foo& operator=(const foo&) = delete;
};
foo&
get_foo()
{
static foo f;
return f;
}
int
main()
{
auto& f = get_foo();
}
如果您使用的是Visual Studio,则需要VS-2015或更高版本。
线程局部静态在c++ 11和以后的版本中具有线程安全初始化。
template <class T>
class Singleton
{
public:
static T& getinstance()
{
static T t;
return t;
}
};
?
但是在最后的分析中,我是KISS的忠实粉丝。没有什么比为单例编写get_foo()
工厂函数更简单的了(多亏了线程安全的函数局部静态)。由于语言现在提供了硬部分(线程安全初始化),class Singleton<T>
增加的价值很小。
这是我最近写的代码,表明我在实践我所说的:
https://github.com/HowardHinnant/date/blob/master/src/tz.cpp L573-L578
在这个特殊的例子中,我需要为我的单例有一个相当复杂的构造过程,甚至需要偶尔重新初始化它的能力。但它仍然归结为一个包裹着function-local-static的工厂函数。
相关文章:
- C++ 实现模板单例类时出现链接错误
- 具有非默认构造函数的单例类
- 单例类析构函数无法清理 (SDL_Quit) MinGW
- 如何在单例类中管理变量状态?
- 访问单例类C++时出现问题
- 基于 IOKit 的 kext 驱动程序中的单例类
- 指向抽象模板单例类的指针向量C++?
- C++在单例类中创建类实例时遇到困难
- 如果我这样写,我的单例类会导致什么错误
- 这是一个有效的单例类吗?
- 函数内具有静态变量的单例类(迈耶实现)
- 继承的模板化单例类 c++ 中未定义的构造函数
- 为什么调用单例类 Qt 消息处理程序成员函数会出现错误:缺少参数列表
- C++:单例类设计(错误:未解析的外部符号)
- 构造函数在不同线程中的静态单例类上调用两次
- 如何在自定义单例类中使用log4cplus
- 为什么在C 中创建单例类创建期间静态函数参考静态变量
- 如何在静态单例类中以编程方式从exec方法返回
- 为什么在单例类中私有析构函数
- c++中的静态对象与单例类对象