Let\'s say I have an object Employee_Storage
that contains a database connection data member. Should this data member be stored as a pointer or as a reference?
Given a choice, I like to use the most constrained type possible. So if I don't need to support null objects I'd much prefer to declare a
Foo& m_foo;
member rather than a
Foo*const m_foo;
member, because the former declaration documents the fact that m_foo
can't be null.
In the short term, the advantage isn't that great. But in the long run, when you come back to old code, the instant assurance that you don't have to worry about the case of m_foo
being null is quite valuable.
There are other ways of achieving a similar effect. One project I worked on where they didn't understand references would insist any potentially null pointers be suffixed '00' e.g m_foo00
. Interestingly, boost::optional
seems to support references although I haven't tried it. Or you can litter your code with assertions.