Given the following example code:
class Room {
Room() : switch(*this) { }
Lamp lamp;
Switch switch;
void TurnOn() { lamp.TurnOn(); }
}
class Switch {
Switch(Room& room) : room(room) { }
Room& room;
void TurnOn() { room.lamp.TurnOn(); }
}
My understanding here is that the second TurnOn()
involves an extra level of indirection, as we need to follow the reference to room. Is this correct? Will that extra indirection be removed if the call can be inlined (either via explicit inlining, or whole program optimization at linker level)? Or, put differently, could the TurnOn function in Switch be sped up by changing it to:
class Room {
Lamp lamp;
Switch switch;
Room() : switch(*this,lamp) { }
void TurnOn() { lamp.TurnOn(); }
}
class Switch {
Room& room;
Lamp& lamp;
Switch(Room& room,Lamp& lamp) : room(room),lamp(lamp) { }
void TurnOn() { lamp.TurnOn(); }
}
Or, more generally, if holding a reference to an object, is there a level of indirection less involved in accessing its members directly via a reference rather than via the reference and then the member?
Thanks