mardi 8 décembre 2015

Meyers Singleton Scope

In the following program, it seems like the Registry Singleton isn't being persisted across calls to the static functions. What is the problem with this approach?

#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;
}

Aucun commentaire:

Enregistrer un commentaire