Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How stl containers destroy objects

Tags:

c++

stl

How does stl call the destructors of objects, as in std::vector::erase or std::vector::pop_back?

like image 215
ConsciousCode Avatar asked Jul 15 '11 00:07

ConsciousCode


2 Answers

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.

like image 91
Steve Townsend Avatar answered Sep 23 '22 17:09

Steve Townsend


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.

like image 33
Kerrek SB Avatar answered Sep 26 '22 17:09

Kerrek SB