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 ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.