简体   繁体   中英

C++17 polymorphic memory recources not working

I was trying to understand the c++17 pmr. So I did this and it is not working as I thought, what could go wrong?

template <typename T>
class Memory : public std::experimental::pmr::memory_resource {
  public:
    Memory() { this->memory = allocate(sizeof(T), alignof(T)); }
    void *getMemory() { return this->memory; }

    ~Memory() { deallocate(this->memory, sizeof(T), alignof(T)); }

  private:
    void *do_allocate(std::size_t bytes, std::size_t alignment)
    {
        memory = ::operator new(bytes);
    }
    void do_deallocate(void *p, std::size_t bytes, std::size_t alignment)
    {
        ::operator delete(memory);
    }
    bool do_is_equal(
           const std::experimental::pmr::memory_resource& other) const noexcept
    {
    }
    void *memory;
};

what can be going wrong with my implementation? This is the client..

Memory<std::string> mem;
std::string * st = (std::string*)mem.getMemory();
st->assign("Pius");
std::cout << *st;

The polymorphic resource allocators allocate memory ; that's all they do. Unlike container Allocators, they don't create objects . That's why they return void* s.

Memory resources are not meant to be used by themselves. That's why std::polymorphic_allocator<T> exists. You can also do the object creation/destruction yourself, using placement- new and manual destructor calls.

Also, your memory_resource implementation makes no sense. do_allocate should return the allocated memory, not store it internally. Your function provokes undefined behavior by returning nothing (which your compiler should have warned about).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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