LearnFrenzy
Sign in Take a free test

Static and Friend Members · Static and Friend Programs · Question 1

Thread-safe singleton configuration manager in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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.

Solution
main.cpp
#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;
}

Output Verified by compiling and running

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.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links