Mendes
Mendes

Reputation: 18441

Correct way to call a singleton object in C++

I'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...

Upvotes: 1

Views: 4674

Answers (2)

Christian Abella
Christian Abella

Reputation: 5797

what about you just call the function like this:

Singleton::getInstance().getMessage("a");

instead of assigning it to a variable.

Upvotes: 6

KompjoeFriek
KompjoeFriek

Reputation: 3875

You want to store a reference to your singleton, not a pointer.

Singleton& my_singleton = Singleton::getInstance();

Upvotes: 1

Related Questions