在 C++ 中调用单例对象的正确方法

Correct way to call a singleton object in C++

我根据命中 posted here 构建了一个单例 class。

我用 getMessage() 函数扩展了它,它将检索内部字典消息 - 字典只需要在整个应用程序上加载一次,这就是单例的原因。

我的代码:

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.";
}

以及主要代码:

main.cpp

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

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

}

Main 给我一个错误:Cannot convert 'Singleton' to 'Singleton*' in assignment

"instantiate" 单例和使用 getMessage 函数的正确方法是什么。

非常感谢您的帮助...

您想存储对单例的引用,而不是指针。

Singleton& my_singleton = Singleton::getInstance();

如果你像这样调用函数呢:

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

而不是将其分配给变量。