Class members that are objects - Pointers or not? C++

后端 未结 11 1906
挽巷
挽巷 2020-12-07 12:59

If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not? What does it mean also to have it as not a

11条回答
  •  有刺的猬
    2020-12-07 13:24

    I follow the following rule: if the member object lives and dies with the encapsulating object, do not use pointers. You will need a pointer if the member object has to outlive the encapsulating object for some reason. Depends on the task at hand.

    Usually you use a pointer if the member object is given to you and not created by you. Then you usually don't have to destroy it either.

提交回复
热议问题