1

I am having trouble changing the memory resource of a map in my custom container. It seems I can neither change the allocator of the map, nor create a new map with the custom memory resource.

#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;
}

https://godbolt.org/z/aVMuw6

How can I reset the container at runtime such that the custom memory resource is used to allocate items in the map?

1 Answer 1

1

You cannot change a container's Allocator after it has been constructed. And even polymorphic_allocator's memory resource cannot be changed after it has been constructed. So what you want isn't really doable; you are expected to know what memory resource your container will use at the time of its construction and that is the allocator+resource that it will use until its destruction.

There are circumstances that would allow you to copy/move/swap a new allocator into a container, but polymorphic_allocator disallows all of them.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I accept that I cannot change it after construction. But I can't even seem to get a new one constructed with a new resource. I guess because the = Map{&resource} calls the assignment copy constructor or something like that? If I change the map to be a unique_ptr then I get it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.