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

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

    Some advantages of pointer member:

    • The child (MyOtherClass) object can have different lifetime than its parent (MyClass).
    • The object can possibly be shared between several MyClass (or other) objects.
    • When compiling the header file for MyClass, the compiler doesn't necessarily have to know the definition of MyOtherClass. You don't have to include its header, thus decreasing compile times.
    • Makes MyClass size smaller. This can be important for performance if your code does a lot of copying of MyClass objects. You can just copy the MyOtherClass pointer and implement some kind of reference counting system.

    Advantages of having the member as an object:

    • You don't have to explicitely write code to create and destroy the object. It's easier and and less error-prone.
    • Makes memory management more efficient because only one block of memory needs to be allocated instead of two.
    • Implementing assignment operators, copy/move constructors etc is much simpler.
    • More intuitive

提交回复
热议问题