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

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

    If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not?

    you should generally declare it as a value in your class. it will be local, there will be less chance for errors, fewer allocations -- ultimately fewer things that could go wrong, and the compiler can always know it is there at a specified offset so... it helps optimization and binary reduction at a few levels. there will be a few cases where you know you'll have to deal with pointer (i.e. polymorphic, shared, requires reallocation), it is typically best to use a pointer only when necessary - especially when it is private/encapsulated.

    What does it mean also to have it as not a pointer in terms of where it is stored in memory?

    its address will be close to (or equal to) this -- gcc (for example) has some advanced options to dump class data (sizes, vtables, offsets)

    Will the object be created when the class is created?

    yes - the size of MyClass will grow by sizeof(MyOtherClass), or more if the compiler realigns it (e.g. to its natural alignment)

提交回复
热议问题