简体   繁体   English

C ++ 17多态内存无法正常工作

[英]C++17 polymorphic memory recources not working

I was trying to understand the c++17 pmr. 我试图了解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. 这就是为什么它们返回void*的原因。

Memory resources are not meant to be used by themselves. 内存资源并不意味着要自己使用。 That's why std::polymorphic_allocator<T> exists. 这就是为什么存在std::polymorphic_allocator<T>的原因。 You can also do the object creation/destruction yourself, using placement- new and manual destructor calls. 您还可以使用“ placement”( new和手动的析构函数调用)自行创建/破坏对象。

Also, your memory_resource implementation makes no sense. 同样,您的memory_resource实现没有任何意义。 do_allocate should return the allocated memory, not store it internally. do_allocate应该返回分配的内存,而不是在内部存储它。 Your function provokes undefined behavior by returning nothing (which your compiler should have warned about). 您的函数通过不返回任何内容(编译器应该警告过)来引发未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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