The idea remains the same for unique_ptr , except for the fact that the type of deleter is part of the unique_ptr type.
#include <functional> #include <memory> #include <iostream> using namespace std; class X { private: ~X() {} class deleter { public: void operator()(X * p) { delete p; } }; friend class deleter; public: static shared_ptr<X> create_shared() { shared_ptr<X> px(new X, X::deleter()); return px; } static unique_ptr<X, void(*)(X*)> create_unique() { return unique_ptr<X, void(*)(X*)>( new X, []( X *x ) { X::deleter()( x ); } ); } // If using VS2010 static unique_ptr<X, std::function<void(X*)>> create_unique() { return unique_ptr<X, std::function<void(X*)>>( new X, X::deleter() ); } }; int main() { auto x = X::create_shared(); auto y = X::create_unique(); }
VS2010 does not implement implicit lambda conversion without capturing to a function pointer, so the first create_unique will not work on it.
source share