Hard
A singleton destructor that uses another singleton
Logger and Config are each Meyer's singletons defined in separate translation units. Logger's destructor writes a shutdown message using Config::instance(). Both singletons get first-used (and thus first-constructed) during main, in the order shown. What happens at program exit?
logger.cpp / config.cpp / main.cpp
// config.cpp
class Config {
public:
static Config& instance() { static Config c; return c; }
std::string get(const std::string& key) { return data_[key]; }
private:
std::unordered_map<std::string, std::string> data_{{"level", "info"}};
};
// logger.cpp
class Logger {
public:
static Logger& instance() { static Logger l; return l; }
~Logger() {
std::cout << "shutdown level=" << Config::instance().get("level") << "\n";
}
};
// main.cpp
int main() {
Config::instance(); // constructed first
Logger::instance(); // constructed second
}2 of 44 in Design Patterns