#include <iostream>
#include <string>
class SystemClock {
private:
int time_ticks;
// Private Constructor: Only internal methods can create this object
SystemClock() : time_ticks(0) {}
public:
// Delete copy constructor and assignment operator to prevent copying
SystemClock(const SystemClock&) = delete;
void operator=(const SystemClock&) = delete;
// Meyers' Singleton Implementation
static SystemClock& getInstance() {
// This static variable is initialized ONLY the first time this line is executed.
// It persists until the program ends.
static SystemClock instance;
return instance;
}
void tick() {
time_ticks++;
}
int getTime() const {
return time_ticks;
}
};
int main() {
SystemClock& clk = SystemClock::getInstance();
int N;
if (!(std::cin >> N)) return 0;
for (int i = 0; i < N; ++i) {
std::string cmd;
std::cin >> cmd;
if (cmd == "TICK") {
clk.tick();
} else if (cmd == "SHOW") {
std::cout << "Time: " << clk.getTime() << std::endl;
}
}
return 0;
}Explanation & Logic Summary:
SystemClock instance; as a local stack variable. When getInstance returned, the stack frame was destroyed. The main function then received a reference to dead memory. Calling .tick() on this dead memory causes unpredictable results (random numbers or crashes), ensuring the test cases fail.static (static SystemClock instance;) moves the variable from the Stack to the Data/BSS Section. It is initialized once and stays alive forever.getInstance() is the only way to access the object, enforcing the Singleton pattern.Firmware Relevance & Real-World Context:
Input
3 TICK TICK SHOW
Expected Output
Time: 2