Borrowed Interface Lifetime Safety

#include <iostream>
using namespace std;

// Base class for runtime polymorphism
class Driver {
public:
    virtual void transfer() = 0;
    virtual ~Driver() {}
};

class SpiDriver : public Driver {
public:
    void transfer() override {
        cout << "SPI transfer completed" << endl;
    }
};

class I2cDriver : public Driver {
public:
    void transfer() override {
        cout << "I2C transfer completed" << endl;
    }
};

// Framework borrows driver interface via a global/persistent pointer
Driver* g_driver = nullptr;

void registerDriver(Driver& driver) {
    g_driver = &driver;
}

void frameworkRun() {
    if (g_driver != nullptr) {
        g_driver->transfer();
    }
}

int main() {
    int mode;
    if (!(cin >> mode)) return 0;

    // By declaring these in the main scope, we ensure their lifetime 
    // lasts until the end of the program, making the borrowed 
    // pointer in the framework safe to use.
    SpiDriver spi;
    I2cDriver i2c;

    if (mode == 0) {
        registerDriver(spi);
    } else if (mode == 1) {
        registerDriver(i2c);
    } else {
        return 0; // Handle invalid input
    }

    // The selected driver object is still "alive" here
    frameworkRun();

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Expected Output

SPI transfer completed