3

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

2 Answers 2

4

You are correctly returning a reference to your singleton, but when you use it you are taking a copy. Offending line follows:

Registry reg = Test::registry(); 

To fix the problem, modify this to:

Registry & reg = Test::registry(); 

To prevent this from ever happening, you can prevent the compiler from allowing copies by deleting the copy constructor and assignment operators:

class Registry : public unordered_map<string,string> { public: Registry() {} Registry( const Registry & ) = delete; Registry & operator=( const Registry & ) = delete; }; 
Sign up to request clarification or add additional context in comments.

Comments

3

Your code makes a copy of the registry in each function call and then throws the copy away.

Instead, you want to make a reference to the one and only registry:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.