Re: std::vector padding behavior and alignment
On Apr 30, 2:29 am, blargg....@gishpuppy.com (blargg) wrote:
Andrew Tomazos wrote:
[Basically asks how vector can allocate reserve space without
calling constructors, and ensure that the space is
appropriately aligned]
Any of the following allocates memory appropriately aligned
for n objects of any type T, without invoking any
constructors:
size_t size = n * sizeof (T);
void* p;
p = new char [size];
p = operator new ( size );
p = operator new [] ( size );
p = malloc( size );
The current standard (ISO/IEC 14882:2003) requires the standard
allocator to use ::operator new( size_t ) to acquire the raw
memory. None of the other techniques are permitted. (A user
defined allocator can use anything it wishes.)
A pointer to a particular object i can be obtained trivially:
T* t = static_cast<T*> (p) + i;
The implementations I've seen do the case directly on the return
value of ::operator new, and maintain the pointers as T*. Of
course, they're very careful not to access any of the elements
as T before they've been constructed, and after they've been
destructed.
The reason for this is probably because they use the internal
pointers very much like iterators, which requires pointer
arithmetic, and pointer arithmetic doesn't work on void*.
I believe, too (although I'm too lazy to verify it) that the
standard requires the containers to use the allocator member
functions construct and destroy for construction and
destruction. The default allocator is required to use placement
new and an explicit call to the destructor; a user defined
allocator can, again, use anything that works (but in this case,
I don't know of anything else that would work).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34