gpt4 book ai didi

c++ - 清除 std::map 的 boost::pool_allocator 不会返回 VS2017 中的整个池

转载 作者:太空狗 更新时间:2023-10-29 21:33:40 24 4
gpt4 key购买 nike

当我在 VS2017 中运行下一个代码时:

#include <boost/pool/pool_alloc.hpp>
#include <map>
#include <iostream>

int main()
{
using Map = std::map<int, int, std::less<int>, boost::pool_allocator<std::pair<const int, int>>>;
using Pool = boost::singleton_pool<boost::pool_allocator_tag, sizeof(Map)>;

Map temp;

for (int i = 1; i < 5; i++) temp[i] = i;

std::cout << "First addresses:\n";
for (auto& kv : temp) std::cout << &kv.second << "\n";

temp.clear();
Pool::purge_memory();

Map temp2;

for (int i = 1; i < 5; i++) temp2[i] = i;

std::cout << "Second addresses:\n";
for (auto& kv : temp2) std::cout << &kv.second << "\n";

temp2.clear();
Pool::purge_memory();

return 0;
}

我得到输出:

First addresses:
02A108F4
02A1090C
02A10924
02A1093C
Second addresses:
02A1090C
02A10924
02A1093C
02A10954

Live example

此行为似乎不正确:地址 02A108F4 发生了什么?似乎在清除过程中没有返回到池中。

当我使用 std::vector 而不是 std::map 时,这不会发生。gcc 似乎也正确返回内存:Live example .

这是 VS2017 中的错误吗?

最佳答案

您假设池的实现细节。你可能是对的,有损失,但你不能从你看到的分配模式中得出结论。

此外,您正在清除与 sizeof(int) 关联的池分配器的内存。 .但是,value_type 已经是 std::pair<int const, int> ,这留下了一个事实,即 map 实现分配了一个未指定的节点类型。

Oh, and the reason your allocator worked is precisely the same: the container implementation knows you cannot possibly provide the right type of allocator, since the allocated type is unspecified. Therefore it will always rebind to get the required type.

所以,至少做到了

Live On Rextester

#include <boost/pool/pool_alloc.hpp>
#include <map>
#include <iostream>

using Map = std::map<int, int, std::less<int>, boost::pool_allocator<int>>;
using Pool = boost::singleton_pool<boost::pool_allocator_tag, sizeof(Map::value_type)>;

void foo() {
Map temp;

for (int i = 1; i < 5; i++) temp[i] = i;

std::cout << "First addresses:\n";
for (auto& kv : temp) std::cout << &kv.second << "\n";
}

int main()
{
foo();
Pool::purge_memory();

foo();
Pool::purge_memory();
}

不过,这仍然是假设实现细节。我认为 c++17 为您提供了更多信息以供使用 (http://en.cppreference.com/w/cpp/container/node_handle),否则您可以查看 Boost Container 是否具有相关详细信息:https://www.boost.org/doc/libs/1_51_0/doc/html/boost/container/map.html#id463544-bb

关于c++ - 清除 std::map 的 boost::pool_allocator 不会返回 VS2017 中的整个池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50529196/

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