简体   繁体   English

stl 容器如何破坏对象

[英]How stl containers destroy objects

How does stl call the destructors of objects, as in std::vector::erase or std::vector::pop_back? stl 如何调用对象的析构函数,如 std::vector::erase 或 std::vector::pop_back?

The vector has an allocator associated with it, the destroy member is used to clean up. vector有一个与之关联的分配器destroy成员用于清理。

Calls an objects destructor without deallocating the memory where the object was stored.调用对象析构函数而不释放存储 object 的 memory。

Incidentally you can follow this through the source yourself, given decent IDE.顺便说一句,鉴于不错的 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.实际上,内部分配是由分配器完成的,它有两个不同的目的:分配和释放 memory,以及构造和销毁对象。 Objects are always (copy or move) constructed on insert and destroyed on erase , however, the interna vary.对象总是(复制或移动)在insert时构造并在erase时销毁,但是,内部会有所不同。

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).基于节点的容器通常会分配和构造一个完整的内部节点,其中包含实际的 object簿记数据(如双向链表中的 next/prev 指针)。 When you erase one of those, the container will destroy the object and release the memory.当您擦除其中一个时,容器将破坏 object 并释放 memory。

Sequence containers like vector will strictly separate allocation and construction;像vector这样的序列容器会严格分离分配和构造; 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.已分配的 memory 的数量通常只会增加,但是当您擦除时(在调用已擦除对象的析构函数之后),必须移动其他元素以保持连续的 memory 布局。

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.如果您以前没有见过内部分配器的工作可能看起来与您通常的new/delete工作完全不同,但最终总会在某处进行构造和破坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM