131. Ownership

Question.2

A Sensor class uses an I2C bus but does not own it:

class Sensor {
   I2C_Bus& bus;  // Reference -- observer, not owner
public:
   Sensor(I2C_Bus& b) : bus(b) {}
   int read() { return bus.read_reg(0x42, 0x00); }
   // No destructor -- does NOT destroy the bus
};

I2C_Bus i2c1;
Sensor temp(i2c1);
Sensor humidity(i2c1);  // Both share the same bus

Who is responsible for the I2C bus lifetime?

Need Help? Refer to the Quick Guide below

Select Answer