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:
- "Whole-object" vector member varaiable containing values, i.e.
vector<MyClass> my_vector;
- Pointer to a vector, i.e
vector<MyClass>* my_vector;
- Vector of pointers, i.e.
vector<MyClass*> my_vector;
- 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!!
A pointer to a
vector
is very rarely useful - avector
is cheap to construct and destruct.For elements in the
vector
, there's no correct answer. How often does thevector
change? How much does it cost to copy-construct the elements in thevector
? Do other containers have references or pointers to thevector
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 asvector
elements.