I have a hipotetichypothetical C++ code containing these two classes:
- Master: it's big, does a lot of things and is meant to have only one instance;
- Slave: quite the opposite. It can also do a lot of things, but it's small, and has many instances.
Every slave needs access to the master, so it is injected through the constructor:
class Slave {
private:
// Few small attributes
Master& master;
public:
Slave(Master& master) master(master) { }
// May have lots of methods...
}
As there are many slaves, each one holding a reference to the master, a lot of memory is wasted in pointers that point to the same thing. I would like to think that the C++ compilers could find a way to optimize that Master& master attribute out of the Slave class, but I don't believe they do it - please, correct me if I'm wrong.
A solution would be to turn the Master class into a Singleton, but that is widely considered an anti-pattern. I think maybe a better approach is to turn the Master& master attribute into a static pointer:
class Slave {
private:
// Attributes...
public:
static Master* master;
Slave() { }
// Methods...
}
It's a pity that the reference needs to be converted to a pointer, but at least this eliminates the memory waste, while preserving the ability to "inject" the master and using a mock for testing.
What do you guys think?