从BOOST或c++ 14类中删除其他单例类中的ACE_Singleton

Removal of ACE_Singleton with some other Singleton class from BOOST or C++14 class

本文关键字:单例类 ACE Singleton 其他 删除 BOOST c++ 14类      更新时间:2023-10-16

我们正在从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的工厂函数。