gpt4 book ai didi

c++ - 如果容器和分配器都属于同一个内存池,我还需要调用 std::container 的析构函数吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:12:08 26 4
gpt4 key购买 nike

(以线程构建 block 内存池为例)

假设我有以下设置:

using MemoryPool = tbb::memory_pool<std::allocator<char>>;
using CustomAllocator = tbb::memory_pool_allocator<Result*>;
using CustomVector = std::vector<Result*, CustomAllocator>;

MemoryPool shortTermPool;
void* allocatedMemory = shortTermPool.malloc(sizeof(CustomVector);
CustomVector* results = static_cast<CustomVector*>(allocatedMemory);
new(results) CustomVector(CustomAllocator(shortTemPool));

稍后我打电话

shortTermPool.recycle(); 

这行代码回收了内存池中的所有内存,让我可以复用。现在,既然 vector 和它的分配器都在使用内存池,我还需要调用吗

results->~vector();

在回收内存池之前?析构函数是否在做任何额外的事情,或者回收整个池就足够了吗?

最佳答案

来自 C++ 标准:

3.8 Object lifetime

4 A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

这取决于 std::vector 析构函数是否是非平凡的并且具有程序所依赖的副作用。因为它是一个库类,为了安全起见还是调用析构函数为宜。否则,您现在和将来都必须检查 std::vector 实现,以了解您希望代码与之兼容的所有标准库。
如果 vector 类是您自己的,您将控制析构函数的实现,并且如果它是微不足道的,或者没有程序所依赖的副作用,您可以省略调用它,如上所述。
(但我个人也会在这种情况下调用它。)

关于c++ - 如果容器和分配器都属于同一个内存池,我还需要调用 std::container 的析构函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com