vectors and memory efficiency

From: Mark P (not_at_my.real.email)
Date: 03/28/05


Date: Mon, 28 Mar 2005 09:42:59 GMT

Say I intend to create some number of instances of a certain class C and
then store them "in some way" in a vector.

One possibility would be to allocate space on the heap as needed:

C* item = new C(args);

and then use a vector<C*> to hold these:

std::vector<C*> pVec;
pVec.push_back(item);

Repeat as needed.

Or I could use a vector<C> to hold the items themselves rather than
their addresses:

std::Vector<C> iVec;
iVec.push_back(C(args));

Again, repeat as needed.

Now I'm wondering about the relative efficiency of these two approaches.
  I've generally opted for the first approach in the interest of
minimizing copying, but now I wonder whether an intelligent compiler
might make the second approach more efficient.

It seems that a vector, knowing that it will hold C items, can allocate
the space for those items in lumps rather than as single items and
perhaps it would be possible to construct the items directly in their
destination memory within the vector. Then again, maybe this isn't
possible, and either way, if the vector is required to reallocate space
this could involve a lot of copying (perhaps mitigated by judicious use
of the reserve() function).

Is there any validity to this and are there general rules that can help
in the decision between these two approaches?

Thanks,
Mark