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

前端 未结 5 2291
耶瑟儿~
耶瑟儿~ 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 16:38

    Adding to this question..

    Class with reference data member:

    • you must pass a value to the object at construction (not unexpectedly)
    • breaks the rule of encapsulation, as referenced variable can be changed from outside class, without class object having any control of it. (I suppose the only use case could be something like this though, for some very specialized reasons.)
    • prevents creating assignment operator. What are you going to copy?
    • you need to ensure the referred variable is not destroyed while your object is alive

提交回复
热议问题