1

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

Community
  • 1
  • 1
Mendes
  • 17,489
  • 35
  • 150
  • 263

2 Answers2

6

what about you just call the function like this:

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

instead of assigning it to a variable.

Christian Abella
  • 5,747
  • 2
  • 30
  • 42
  • Doesn´work and doesn´t make sense that I cannot store it in a variable...I need to fix howto store it in a variable, not to avoid it... – Mendes Apr 22 '15 at 23:55
  • Actually this gave me a hint on how to solve it... Singleton& my_singleton = Singleton::getInstance(); then my_singleton.getMessage("a"); – Mendes Apr 23 '15 at 00:01
  • 2
    @Mendez no need the reference: just type it as: `Singleton::getInstance().getMessage("a");` if you want to short it use a macro: `#define theSingleton Singleton::getInstance()` and use it with the macro: `theSingleton.getMessage("a");` – SHR Apr 23 '15 at 00:04
1

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

Singleton& my_singleton = Singleton::getInstance();
KompjoeFriek
  • 3,572
  • 1
  • 22
  • 35
  • Not worked. Compiler generated error 'singleton' declared as reference but not initialized and several others on Singleton code... – Mendes Apr 22 '15 at 23:45
  • @Mendez You need to declare it and initialize in the same expression like in the code above – yachoor Apr 22 '15 at 23:52
  • 1
    I'm using the exact same `Singleton` in my own code all the time, it should work. But i prefer to access it like @Christian (and with a `dot` instead of `->`) – KompjoeFriek Apr 22 '15 at 23:53
  • @Mendez Please see that my answer does work in this online example: http://goo.gl/B9Ws4P – KompjoeFriek Apr 23 '15 at 00:03