Lazy Static Singleton

#include <iostream>
#include <string>

class SystemClock {
private:
    int time_ticks;

    // TODO: Make Constructor Private so users cannot do 'SystemClock c;'
    // SystemClock() : time_ticks(0) {}
    SystemClock() : time_ticks(0){}

public:
    // TODO: Implement Static method getInstance()
    static SystemClock& getInstance() {
        // ERROR: This creates a local variable that is destroyed when the function ends.
        // Returning a reference to it leads to Undefined Behavior (garbage values).
        // TODO: Fix this by making 'instance' static.
        static SystemClock instance; 
        return instance;
    }

    void tick() {
        time_ticks++;
    }

    int getTime() const {
        return time_ticks;
    }
    
};

int main() {
    // This line tries to get the global instance
    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(); // accessing dangling reference -> Crash or Garbage
        } else if (cmd == "SHOW") {
            std::cout << "Time: " << clk.getTime() << std::endl;
        }
    }
    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

3 TICK TICK SHOW

Expected Output

Time: 2