shared_ptr删除器问题

时间:2016-06-27 03:35:41

标签: c++ templates c++14 shared-ptr

我正在尝试在shared_ptr中附加删除功能,因为我们想要汇集我的内存但却出现了一个奇怪的错误。请帮我解决这个错误:

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

错误是:

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)); 

1 个答案:

答案 0 :(得分:2)

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

您可以改为使用lambda:

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

但是如果你必须使用std::bind,你必须这样做:

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