samedi 20 avril 2019

How to de-allocating the memory allocated using std::memory_resource in static method without changing the below function signature

How can we de-allocate the memory allocated in static member function using std::memory_resource::allocate()?

I tried using deleter function passing to the unique_ptr instead of default_delete.In that case it is freeing the allocator memory. The problem is i am not sure about the allocator object lifetime till the end of unique_ptr going out of scope & i dont want to change the static function signature below form using deleter method. eg:

static std::unique_ptr<base,std::functional<void(base*)>> create(std::pmr::memory_resource* all)
  {
    void* ptr = all->allocate(sizeof(base));
    std::unique_ptr<base, std::function<void(base*)> up(new base(), [&all] 
     (base* b){ all->deallocate(b,sizeof(base));
    return std::move(up);
  }

//Actual source code

#define _CRTDBG_MAP_ALLOC 
#include <iostream>
#include <memory_resource>
#include <memory>
#include <functional>

using namespace std;

class base
{
  int val = 0;
public:
  base()
  {

  }
  ~base()
  {
    cout << "dest" << endl;
  }
  static std::unique_ptr<base> create(std::pmr::memory_resource* all)
  {
    void* ptr = all->allocate(sizeof(base));
    return std::unique_ptr<base>(new(ptr) base());
  }
};

int main()
{
  {
    {
      std::pmr::memory_resource* all = std::pmr::get_default_resource();
      auto b1 = base::create(all);
      auto b2 = base::create(all);
    }
    _CrtDumpMemoryLeaks();
  }
  return 0;
}

i want to free the memory allocated in the static method without modifying the function signature(means adding the deleter function to the unique_ptr). Suggest any solution to solve this problem & pls also mention different ways of freeing the memory allocated in this sample code via allocate().

Aucun commentaire:

Enregistrer un commentaire