Search code examples
c++c++11boostc++14

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


We are migrating from C++03 to C++14 and it is the decision to go way from ACE lib. We mostly use ACE lib for Singleton objects and locks. So for locks we can use mutex from C++11/14 but what would be the better replacement of ACE_SINGLETON.


Solution

  • #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();
    }
    

    If you are using Visual Studio, you need VS-2015 or later.

    Thread-local statics have thread safe initialization in C++11 and forward.

    Update

    template <class T>
    class Singleton
    {
    public:
        static T& getinstance()
        {
            static T t;
            return t;
        }
    };
    

    ?

    But in the final analysis, I'm a big fan of KISS. And there's nothing much simpler than writing a get_foo() factory function for your singleton (thanks to thread-safe function local statics). Since the language now supplies the hard part (thread safe initialization), class Singleton<T> adds little value imho.

    Here is recent code I've written indicating that I practice what I'm saying:

    https://github.com/HowardHinnant/date/blob/master/src/tz.cpp#L573-L578

    In this particular case I needed to have a quite complicated construction process for my singleton, and even the ability to occasionally re-initialize it. But it still boiled down to a factory function wrapped around a function-local-static.