Write a ConfigManager singleton that stores key/value settings, prevents copying, and is created only on first use. Show that two references refer to the same object.
#include <iostream>
#include <map>
#include <string>
class ConfigManager {
std::map<std::string, std::string> values_;
ConfigManager() { std::cout << "[created]\n"; }
public:
static ConfigManager& instance() {
static ConfigManager cm; // lazy, thread-safe since C++11
return cm;
}
ConfigManager(const ConfigManager&) = delete;
ConfigManager& operator=(const ConfigManager&) = delete;
void set(const std::string& k, const std::string& v) { values_[k] = v; }
std::string get(const std::string& k, const std::string& def = "") const {
auto it = values_.find(k);
return it == values_.end() ? def : it->second;
}
};
int main() {
std::cout << "app started\n";
ConfigManager::instance().set("theme", "dark");
ConfigManager& a = ConfigManager::instance();
ConfigManager& b = ConfigManager::instance();
b.set("lang", "hi-IN");
std::cout << a.get("theme") << ' ' << a.get("lang") << ' ' << a.get("font", "default") << ' ' << (&a == &b) << '\n';
return 0;
}
app started [created] dark hi-IN default 1
The object is created the first time instance() runs, and the deleted copy operations guarantee nobody can make a second one. Both references point to the same object.