SpOiLeR said:
On Tue, 1 Mar 2005 00:03:12 -0500, Victor Bazarov wrote:
AIUI, there are two instances where you want to have a vector of some
pointer
type. One is when you want to store a pointer to a base class and maintain
polymorphic access to objects of [different] derived types, and the other
one
is when the lifetime of the objects is not necessarily controlled by the
object's visibility. Of course you can have both instances together, they
are not mutually exclusive, but rather orthogonal.
V
What if I have a vector of really BigObject? I mean, when vector gets
resized it must: allocate more memory, call copy constructors for all
elements and finally call destructors after copy is done. For BigObject
this results in both memory and speed performance loss. Wouldn't this be
the third type of situation when it is better to hold pointers in vector
than objects itself? Here, by pointers I mean some kind of smart objects
that are smaller than original objects and do creation/destruction of
BigObject automatically. Copying these pointer objects wouldn't touch
BigObjects on the heap, just pointers to them, which is probably faster,
and definitely uses less "temporary" memory.
If you anticipate frequent resizing of your container, perhaps std::vector
is not the best choice? See other threads and publications to learn more
on how to pick the proper container for your needs.
Hm, but let's say I need random access to container elements. This is
allowed only by vector container (I simulated it with std::list using
iterator that always started from begin() and moved through list until
specified member reached, but of course it was slower than vector). If I
expect from 100 to few 1000s BigObjects to be stored in container, and if I
need random access, but also expect objects will be freely inserted/removed
than what's better: list or vector.
deque.
Using vector, reallocation takes quite
a time (and reserving vector memory for, let's say 10000, BigObjects each
time seems quite a waste), but using list access takes longer time. The
only thing that seems to solve this problem is vector of pointers. The
question is, how to do it safely? I've been googling around and found boost
smart_ptr library which could do the trick.
Probably.
Anyway, all I wanted to say, is that maybe this is another situation where
pointers in vector (and vector specifically, not STL containers generally)
may be needed when performance is considered.