On Tue, 28 Oct 2003 10:12:00 -0000, "Lasse Skyum" <lskyum(AT)mail.dk>
wrote:
I'm currently learning STL and I hate not knowing what is gooing on "inside"
STL... not because I really _need_ to know it to develop my game project,
but that's just my nature... like most of you at this grounp I suspect.
So the question is:
How does a std::vector construct and destruct the elements in it? I know it
has something to do with an allocator...
Suppose I wrote:
CMyClass *pDynArray = (CMyClass*)malloc(sizeof(CMyClass)*100);
Would it then be posible to construct/destruct the elements one by one in
that array?
Yes:
CMyClass initialValue(whatever);
for (int i = 0; i < 100; ++i)
{
//placement new just constructs at the location passed.
//Here we are copying an initialValue, just as vector does.
new(pDynArray + i) CMyClass(initialValue);
}
and destruction (order reversed for fun):
for (int i = 99; i >= 0; --i)
{
//direct destructor calls:
pDynArray[i].~CMyClass();
}
//and of course (unless you want to reuse the memory)
free(pDynArray);
std::allocator uses operator new and operator delete rather than
malloc and free.
That's essentially what goes on inside std::vector, although it
sometimes delegates to the functions allocator::construct (which does
placement new with a copy as above) and allocator::destroy (which just
calls the destructor as above). There is also the algorithm
uninitialized_fill, which essentially performs the loop above on an
iterator range.
Tom