100. RAII Shutdown Ordering

#include <iostream>
using namespace std;

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

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

class Bus {
private:
    Clock& clk;

public:
    Bus(Clock& c) : clk(c) {
        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;

public:
    Driver(Bus& b) : bus(b) {
        cout << "Driver started" << endl;
    }

    void operate(int addr, int val) {
        bus.write(addr, val);
    }

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

class SystemController {
private:
    Clock clk;
    Bus bus;
    Driver drv;

public:
    SystemController() : bus(clk), drv(bus) {}

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

int main() {
    int addr, val;
    cin >> addr >> val;

    {
        SystemController sys;
        sys.run(addr, val);
    }

    return 0;
}

Explanation & Logic Summary

SystemController owns all system components.
The construction order guarantees that the Clock exists before the Bus, and the Bus exists before the Driver.
When SystemController goes out of scope, destructors run automatically in reverse order, ensuring correct shutdown without explicit cleanup logic.

Firmware Relevance & Real-World Context

In real embedded systems, incorrect shutdown ordering can corrupt registers, lock communication buses, or waste power by leaving clocks enabled.
Using RAII with composition encodes lifecycle rules directly into the program structure, making firmware safer, more deterministic, and easier to maintain.

 

 

 

Loading...

Input

5 10

Expected Output

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