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