Reputation: 583
How does stl call the destructors of objects, as in std::vector::erase or std::vector::pop_back?
Upvotes: 5
Views: 652
Reputation: 477670
Perhaps some additions to Steve's nice answer:
Indeed, internal allocation is done by allocators, which serve two separate purposes: Allocating and releasing memory, and constructing and destroying objects. Objects are always (copy or move) constructed on insert
and destroyed on erase
, however, the interna vary.
Node-based containers will typically allocate and construct an entire internal node, which contains both the actual object and bookkeeping data (like the next/prev pointers in a doubly-linked list). When you erase one of those, the container will destroy the object and release the memory.
Sequence containers like vector will strictly separate allocation and construction; the amount of memory that's been allocated will typically only grow, but when you erase (after the erased object's destructor has been called), the other elements have to be moved to maintain contiguous memory layout.
The internal allocator work may look quite different from your usual new/delete
work if you haven't seen it before, but ultimately there's always a construction and a destruction somewhere.
Upvotes: 4
Reputation: 54178
The vector
has an allocator associated with it, the destroy member is used to clean up.
Calls an objects destructor without deallocating the memory where the object was stored.
Incidentally you can follow this through the source yourself, given decent IDE.
Upvotes: 6