Using 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access