2
在下面的程序中,似乎註冊表單例不會在對靜態函數的調用中持久化。這種方法有什麼問題?Meyers Singleton Scope
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
class Test {
typedef unordered_map<string,string> Registry;
public:
static Registry ®istry() {
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;
}