【发布时间】:2020-07-20 19:23:30
【问题描述】:
我无法更改自定义容器中地图的内存资源。 看来我既不能更改地图的分配器,也不能使用自定义内存资源创建新地图。
#include <iostream>
#include <memory_resource>
#include <map>
using Map = std::pmr::map<const std::string, int>;
class custom_resource : public std::pmr::memory_resource {
public:
void* do_allocate(std::size_t bytes, std::size_t alignment) override {
std::cout << "Using custom resource" << std::endl;
return std::pmr::get_default_resource()->allocate(bytes, alignment);
}
void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override {
}
bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override {
return false;
}
};
struct MyContainer {
void Reset(std::pmr::memory_resource &resource)
{
map_ = Map{&resource};
}
void AddItem(std::string k) {
map_[k] = 1;
}
std::pmr::memory_resource* default_resource = std::pmr::get_default_resource();
// custom_resource custom{}; // uncomment this and next line to see it work
// Map map_{&custom};
Map map_{default_resource};
};
int main() {
MyContainer container{};
container.AddItem("a"); // no output expected
custom_resource custom{};
container.Reset(custom);
container.AddItem("b"); // output expected
return 0;
}
如何在运行时重置容器,以便使用自定义内存资源分配地图中的项目?
【问题讨论】:
标签: c++ memory-management c++17 dynamic-memory-allocation