When is it preferable to store data members as references instead of pointers?

前端 未结 5 2436
耶瑟儿~
耶瑟儿~ 2021-02-20 16:33

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?

5条回答
  •  误落风尘
    2021-02-20 17:04

    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.

提交回复
热议问题