Search code examples
c++templatesc++14shared-ptr

shared_ptr deleter issue


I am trying to attach deleter function in shared_ptr as we want to pool my memory but getting an strange error. Please help me to resolve this error:

template<std::size_t size> class Allocator{
public:
    template<typename T> void Release(T *ptr)
    {

    }
    template<typename T> void GetMemory(std::shared_ptr<T> &item)
    {
        T *ptr = new T();
        //my pain point is
        item =  std::shared_ptr<T>(ptr, 
        std::bind(&Allocator<size>::Release, this, std::placeholders::_1));
    }
};

The error is:

prog.cpp: In instantiation of 'void GetMemory(std::share_ptr<T> &item)  unsigned int size = 10u]':
prog.cpp:316:15:   required from here
prog.cpp:226:19: error: no matching function for call to 'bind(<unresolved overloaded function type>, Pool<10u>*, const std::_Placeholder<1>&)'
          std::bind(&Pool<test>::Release, this, std::placeholders::_1)); 

Solution

  • template<std::size_t size> class Allocator{
    public:
        template<typename T> void Release(T *ptr)
        {
    
        }
        template<typename T> void GetMemory(std::share_ptr<T> &item)
        {
            T *ptr = new T();
            //my pain point is
            item =  std::shared_ptr<T>(ptr, 
            std::bind(&Allocator<size>::Release, this, std::placeholders::_1));
        }
    };
    

    You can use a lambda instead:

    item =  std::shared_ptr<T>(ptr, [&](auto x) { this->Release(x); });
    

    But if you must use std::bind, you have to do this:

    item =  std::shared_ptr<T>(ptr, 
        std::bind(&Allocator<size>::template Release<T>, this, std::placeholders::_1));