开发者

How stl containers destroy objects

开发者 https://www.devze.com 2023-03-20 16:29 出处:网络
How does stl call the destructors of objects, as in std::vector::erase开发者_Go百科 or std::vector::pop_back?The vector has an allocator associated with it, the destroy member is used to clean up.

How does stl call the destructors of objects, as in std::vector::erase开发者_Go百科 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消