Meyers Singleton Scope

时间:2015-12-09 00:03:38

标签: c++ design-patterns singleton

在下面的程序中,似乎Registry Singleton不会在调用静态函数时保持不变。这种方法有什么问题?

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

class Test {
typedef unordered_map<string,string> Registry;
public:
    static Registry &registry() {
        static Registry reg;
        return reg;
    }

    static void put(string key, string val) {
        Registry reg = Test::registry();
        reg[key] = val;
    }

    static string get(string key) {
        Registry reg = Test::registry();
        return reg[key];
    }
};

int main() {
    Test::put("a", "apple");
    Test::put("b", "banana");
    cout << Test::get("a") << endl;
    cout << Test::get("b") << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:4)

您正确地返回对您的单身人士的引用,但是当您使用它时,您正在复制。违规行如下:

Registry reg = Test::registry();

要解决此问题,请将其修改为:

Registry & reg = Test::registry();

为了防止这种情况发生,您可以通过删除复制构造函数和赋值运算符来阻止编译器允许复制:

class Registry : public unordered_map<string,string>
{
    public:
        Registry() {}
        Registry( const Registry & ) = delete;
        Registry & operator=( const Registry & ) = delete;
};

答案 1 :(得分:3)

您的代码会在每个函数调用中复制注册表,然后将副本抛出。

相反,您希望为唯一的注册表创建引用

Registry & reg = Test::registry();
//      ^^^