construct
The push_back
function calls chk_n_alloc
to ensure that there is room for an element. When chk_n_alloc
returns, push_back
knows that there is room for the new element. It asks its alloc
member to construct
a new last element:
void StrVec::push_back(const string& s)
{
chk_n_alloc(); // ensure that there is room for another element
// construct a copy of s in the element to which first_free points
alloc.construct(first_free++, s);
}
When we use an allocator
, we must remember that the memory is unconstructed (§ 12.2.2, p. 482). To use this raw memory we must call construct
, which will construct an object in that memory. The first argument to construct
must be a pointer to unconstructed space allocated by a call to allocate
. The remaining arguments determine which constructor to use to construct the object that will go in that space. In this case, there is only one additional argument. That argument has type string
, so this call uses the string
copy constructor.
It is worth noting that the call to construct
also increments first_free
to indicate that a new element has been constructed. It uses the postfix increment (§ 4.5, p. 147), so this call constructs an object in the current value of first_free
and increments first_free
to point to the next, unconstructed element.