140. Lazy Static Singleton

#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:

  • The Bug in Template: The template created 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.
  • The Fix: Adding static (static SystemClock instance;) moves the variable from the Stack to the Data/BSS Section. It is initialized once and stays alive forever.
  • Private Constructor: This ensures that getInstance() is the only way to access the object, enforcing the Singleton pattern.

Firmware Relevance & Real-World Context:

  • Hardware Managers: You only have one physical I2C controller. You want one class instance to manage it.
  • Lazy Loading: In embedded systems with slow boot times, you might want to delay initializing the File System object until you actually try to write a log, rather than doing it all at startup. This pattern handles that automatically.

 

 

 

Loading...

Input

3 TICK TICK SHOW

Expected Output

Time: 2