Effective C++: user-defined deleter.

 #include <iostream>
#include <memory>
#include <functional>
#include <vector>
class Deleter{
 public:
  template<typename T>
  void operator()(T* pointer)noexcept
  {
   delete pointer;
   pointer = nullptr;
   std::cout<<"user-defined Deleter"<<std::endl;
  }
};
auto UserDeleter = std::bind(Deleter(), std::placeholders::_1);
template<typename Ty>
std::unique_ptr<int, decltype(UserDeleter)> make_unique(Ty&& params)
{
 std::unique_ptr<int, decltype(UserDeleter)> temp_unique(nullptr, UserDeleter);
 temp_unique.reset(new int(params));
 
 std::cout<<"enter unique"<<std::endl;
 return temp_unique;  
}
int main()
{
 std::vector<std::function<void()>> filter;
 std::vector<std::function<void(int*)>> filterTwo;
 
 std::unique_ptr<int, decltype(UserDeleter)> first = make_unique(10); //ok!!!!!!
 std::function<void(int*)> f1 = std::bind(Deleter(), std::placeholders::_1);
 filterTwo.push_back(f1);
 
 std::function<void()> fun1 = [](){ std::cout<<"test"<<std::endl; };
 std::function<void()> fun2 = std::bind([](const int& number){ std::cout<<number<<std::endl;}, 10);
 filter.push_back(fun1);
 filter.push_back(fun2);
 
 return 0;
}

你可能感兴趣的:(Effective C++: user-defined deleter.)