How does stl call the destructors of objects, as in std::vector::erase or std::vector::pop_back?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With