pointer vs non-pointer members of a class

前端 未结 5 1127
深忆病人
深忆病人 2021-02-02 02:26

My questions is, suppose we have two classes A and B. I want to have an object of B in class A.

Should I use,

class A
{
  public:
          A();
                 


        
5条回答
  •  春和景丽
    2021-02-02 02:57

    Second one is more convenient , because you don't need to manage memory yourself. No new, no delete.

    If you go with the first one, then you probably have to implement Rule of Three also (in C++03):

    • What is The Rule of Three?

    Or, Rule of Five (in C++11):

    • Rule-of-Three becomes Rule-of-Five with C++11?

    The underlying idea behind this rule is the following:

    • Resource Acquisition Is Initialization

    So unless you've strong reason why you need pointer version (such as in case when you need polymorphic behavior), you must go with the second approach (the non-pointer approach).

提交回复
热议问题