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

后端 未结 11 1934
挽巷
挽巷 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:23

    This question could be deliberated endlessly, but the basics are:

    If MyOtherClass is not a pointer:

    • The creation and destruction of MyOtherClass is automatic, which can reduce bugs.
    • The memory used by MyOtherClass is local to the MyClassInstance, which could improve performance.

    If MyOtherClass is a pointer:

    • The creation and destruction of MyOtherClass is your responsibility
    • MyOtherClass may be NULL, which could have meaning in your context and could save memory
    • Two instances of MyClass could share the same MyOtherClass

提交回复
热议问题