Pointer to vector vs vector of pointers vs pointer

2019-03-11 10:39发布

Just wondering what you think is the best practice regarding vectors in C++.

If I have a class containing a vector member variable. When should this vector be declared a:

  1. "Whole-object" vector member varaiable containing values, i.e. vector<MyClass> my_vector;
  2. Pointer to a vector, i.e vector<MyClass>* my_vector;
  3. Vector of pointers, i.e. vector<MyClass*> my_vector;
  4. Pointer to vector of pointers, i.e. vector<MyClass*>* my_vector;

I have a specific example in one of my classes where I have currently declared a vector as case 4, i.e. vector<AnotherClass*>* my_vector; where AnotherClass is another of the classes I have created.

Then, in the initialization list of my constructor, I create the vector using new:

MyClass::MyClass()
: my_vector(new vector<AnotherClass*>())
{}

In my destructor I do the following:

MyClass::~MyClass()
{
  for (int i=my_vector->size(); i>0; i--)
  {
    delete my_vector->at(i-1);
  }
  delete my_vector;
}

The elements of the vectors are added in one of the methods of my class. I cannot know how many objects will be added to my vector in advance. That is decided when the code executes, based on parsing an xml-file.

Is this good practice? Or should the vector instead be declared as one of the other cases 1, 2 or 3 ?

When to use which case?

I know the elements of a vector should be pointers if they are subclasses of another class (polymorphism). But should pointers be used in any other cases ?

Thank you very much!!

7条回答
聊天终结者
2楼-- · 2019-03-11 11:22

A pointer to a vector is very rarely useful - a vector is cheap to construct and destruct.

For elements in the vector, there's no correct answer. How often does the vector change? How much does it cost to copy-construct the elements in the vector? Do other containers have references or pointers to the vector elements?

As a rule of thumb, I'd go with no pointers until you see or measure that the copying of your classes is expensive. And of course the case you mentioned, where you store various subclasses of a base class in the vector, will require pointers.

A reference counting smart pointer like boost::shared_ptr will likely be the best choice if your design would otherwise require you to use pointers as vector elements.

查看更多
登录 后发表回答