mercredi 22 avril 2015

C++ Correct way to call a singleton object

dI´ve build a singleton class based on the hit posted here...

I´ve extended it with a getMessage() function, that will retrive an internal dictionary message - the dictionary needs to be loaded only once on the whole application, that is the reason of the singleton.

My code:

Singleton.hpp

class Singleton {

public:

    static Singleton& getInstance();
    std::string getMessage(std::string code);

private:

    Singleton() {}; 
    Singleton(Singleton const&) = delete;
    void operator=(Singleton const&) = delete;
};

Singleton.cpp

Singleton& Singleton::getInstance()
{
    static Singleton instance;
    return instance;
}


std::string Singleton::getMessage(std::string code)
{
    /// Do something
    return "Code example.";
}

And the main code:

main.cpp

int main()
{
        Singleton* my_singleton;
        my_singleton = Singleton::getInstance(); **<-- ERROR HERE**

        cout << my_singleton->getMessage("a"); << endl

}

Main is giving me an error: Cannot convert 'Singleton' to 'Singleton*' in assignment

What is the correct way to "instantiate" the singleton and make use of the getMessage function.

Thanks a lot for helping...

Aucun commentaire:

Enregistrer un commentaire