RAII Shutdown Ordering

#include <iostream>
using namespace std;

class Clock {
public:
    Clock() {
        cout << "Clock enabled" << endl;
    }

    ~Clock() {
        cout << "Clock disabled" << endl;
    }
};

class Bus {
public:
    Bus() {
        cout << "Bus initialized" << endl;
    }

    ~Bus() {
        cout << "Bus stopped" << endl;
    }

    void write(int addr, int val) {
        cout << "Bus write: " << addr << " " << val << endl;
    }
};

class Driver {
private:
    Bus& bus_ref; // Driver depends on Bus
public:
    // Constructor receives a reference to the Bus it will use
    Driver(Bus& b) : bus_ref(b) {
        cout << "Driver started" << endl;
    }

    void operate(int addr, int val) {
        // Trigger the bus write operation
        bus_ref.write(addr, val);
    }

    ~Driver() {
        cout << "Driver stopped" << endl;
    }
};

class SystemController {
private:
    // CRITICAL: Order matters! 
    // They are initialized Top -> Bottom
    // They are destroyed Bottom -> Top (RAII)
    Clock clock;
    Bus bus;
    Driver driver;

public:
    // Initialize driver by passing the bus member into it
    SystemController() : clock(), bus(), driver(bus) {}

    void run(int addr, int val) {
        driver.operate(addr, val);
    }
};

int main() {
    int addr, val;
    if (!(cin >> addr >> val)) return 0;

    {
        SystemController sys;
        sys.run(addr, val);
    } // 'sys' goes out of scope here, triggering destructors in reverse order

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

5 10

Expected Output

Clock enabled Bus initialized Driver started Bus write: 5 10 Driver stopped Bus stopped Clock disabled