std::vector padding behavior and alignment
Please consider the following:
We construct a std::vector, push_back 1000 items and then destroy it.
Each normal constructor. copy constructor and destructor is counted...
#include <vector>
#include <cstdio>
class A
{
public:
A(int x) : m_x(x) { s_iConstructs++; }
A(const A& a) { s_iCopies++; }
~A() { s_iDestructs++; }
static void dump()
{
std::printf("s_iConstructs == %d\n", s_iConstructs);
std::printf("s_iCopies == %d\n", s_iCopies);
std::printf("s_iDestructs == %d\n", s_iDestructs);
}
private:
int m_x;
static int s_iConstructs;
static int s_iCopies;
static int s_iDestructs;
};
int A::s_iConstructs(0);
int A::s_iCopies(0);
int A::s_iDestructs(0);
int main(int argc, char** argv)
{
{
std::vector<A> v;
for (int i = 0; i < 1000; i++)
v.push_back(A(i));
}
A::dump();
}
The output from gcc version 4.3.2:
s_iConstructs == 1000
s_iCopies == 2023
s_iDestructs == 3023
The output from Microsoft C/C++ Compiler v15.x:
s_iConstructs == 1000
s_iCopies == 3137
s_iDestructs == 4137
Clearly when a new item is pushed onto the vector, the underlying
memory is not reallocated each time. If it were, the number of copy
constructor calls would be closer to 500,000. Instead they are closer
to 3,000.
Furthermore as type A has no default constructor, we must conclude
that std::vector is heap allocating an uninitialized buffer beyond the
size that it requires, and leaving that extra area uninitialized.
It must allocate its buffer with malloc and not with new[], as new[]
requires that the type be default constructable. (Is this correct?)
When a new item is pushed, it must be using placement new to copy
construct the items in-place over this uninitialized memory.
Now some types have certain alignment restrictions (such as being 4-
byte aligned or 16-byte aligned to the memory address space).
When new SomeAlignedType[1000] is called, the new[] memory allocator
must be aware of these alignment requirements, and select an
appropriately aligned section of memory for the type.
My question is this: How can std::vector use malloc and still respect
these alignment restrictions? By what method does std::vector detect
the alignment requirements of a certain type, and then by what method
does it allocate its array?
If the answer is implementation dependent than specifically how does
gcc and msvc do it?
Is this facility documented and available to user-defined container
types?
Thanks,
Andrew.