pointer vs non-pointer members of a class

2019-03-11 07:19发布

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();
          ~A();
          B* b;
};

or

class A
{
      public:
              A();
              ~A();
              B b;
};

As far as I know, in the first scenario, I can initialize the object *b using new operator and for the second scenario, I can initialize b using an initialization list if I don't want to use the default constructor of class B. Which is more convenient to use?

标签: c++ class
5条回答
Evening l夕情丶
2楼-- · 2019-03-11 07:44

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):

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

The underlying idea behind this rule is the following:

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).

查看更多
Evening l夕情丶
3楼-- · 2019-03-11 07:46

If you want an object of class B in A, then you must use the second. The first doesn't give you an object of type B in A, it gives you an object of type B* in A.

The second is also more convenient for almost all purposes. Only use a pointer when you have to, and even then resource-handling is more convenient with a smart pointer rather than a B*.

查看更多
成全新的幸福
4楼-- · 2019-03-11 07:47

In this scenario, the non-pointer version is more convenient. You don't need to worry about invoking delete at the correct time, and therefore you don't need to worry about destructors, copy constructors and copy assignment operators.

In general, you should avoid dynamically-allocated memory as much as possible.

查看更多
该账号已被封号
5楼-- · 2019-03-11 07:56

Use the second, try to avoid using new as much as possible in C++ unless you are using RAII.

查看更多
Luminary・发光体
6楼-- · 2019-03-11 08:10

It depends.

Even if you use the pointer, you can initialize the member in the initialization list, but that's not your biggest concern.

There are advantages and disadvantages to both:

Using a pointer:

Pros:

  • the class will be smaller in memory

  • you only need a forward declaration to the other class - no need to include the other header in your header

  • can use derived objects from B as members

Cons:

  • memory management - this is a pretty big one. Do you want the memory to be managed by the class (override destructor, assignment operator and copy constructor)?

Using an object:

Pros:

  • no need to worry about memory management

Cons:

  • can only use objects of the base class. What if you want to derive from B?

  • more memory for each instance

  • constructor of B will be called on construction of A

  • you need the full definition of B inside the header

I'll edit my answer if I think of more.

查看更多
登录 后发表回答