whitwhoa
whitwhoa

Reputation: 2489

Initializing a c++ 11 style singleton

Say I have a singleton class App of which I obtain the instance of via:

App& App::get()
{
    static App instance;
    return instance;
}

From my research, when a singleton is required, this is apparently the best way to obtain it's instance. Suppose however that I need to pass a value once during the initial instantiation such as:

void App::init(bool someValue)
{
    static App instance(someValue);
}

Where I'm struggling with this concept is how then can I obtain that instance via the get() method without having to pass someValue every time?

In the past within init() I would simply create an App instance using the constructor, passing the initialization values and save that instance as a static member to the App class, then get() would return that single instance. I seem to be having trouble figuring out how to translate that behavior into this new paradigm. What is the best way to accomplish this?

Upvotes: 1

Views: 730

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

Well, you could have a static pointer which points to a local static instance in init:

// App.hpp
#include <cassert>

class App {
public:
    static void init(bool const b) noexcept {
        static App ap{b};
        _inst = &ap;
    }

    static App& get() noexcept {
        assert(_inst);
        return *_inst;
    }
private:
    App(bool const b)
        : _b{ b }
    {}

    bool _b;
    static App* _inst;
};

// App.cpp

App* App::_inst = nullptr;

// main.cpp

int main() {
    App::init(true);
    auto& ap = App::get(); 
}

Upvotes: 2

Related Questions