shared_ptr允许自定义一个Deleter
#include <iostream>#include <memory>using namespace std;class T {private:static int id;int tid;public:T() {tid = id++;cout << "id = " << tid << " constructor called" << endl;}~T() {cout << "id = " << tid << " destructor called" << endl;}};int T::id = 1;void delete_T(T *){cout << "delete T" <<endl;}int main() {cout << "--------begin-----------" << endl;{shared_ptr<T> t1(new T,delete_T);}cout << "--------end-----------" << endl;return 0;}

在 delete_T 中没有使用delete,t1的析构函数没有调用。
正确做法
#include <iostream>#include <memory>using namespace std;class T {private:static int id;int tid;public:T() {tid = id++;cout << "id = " << tid << " constructor called" << endl;}~T() {cout << "id = " << tid << " destructor called" << endl;}};int T::id = 1;void delete_T(T *t){cout << "delete T" <<endl;delete t; // 在deleter中要手动delete}int main() {cout << "--------begin-----------" << endl;{shared_ptr<T> t1(new T,delete_T);}cout << "--------end-----------" << endl;return 0;}
写成模板
#include <iostream>#include <memory>using namespace std;class T {private:static int id;int tid;public:T() {tid = id++;cout << "id = " << tid << " constructor called" << endl;}~T() {cout << "id = " << tid << " destructor called" << endl;}};int T::id = 1;template<typename _T>void delete_T(_T *t){cout << "delete T" <<endl;delete t;}int main() {cout << "--------begin-----------" << endl;{shared_ptr<T> t1(new T,delete_T<T>);}cout << "--------end-----------" << endl;return 0;}
#include <iostream>#include <memory>using namespace std;class T {private:static int id;int tid;public:T() {tid = id++;cout << "id = " << tid << " constructor called" << endl;}~T() {cout << "id = " << tid << " destructor called" << endl;}};int T::id = 1;void deleter1(T *t) {cout << "deleter 1" << endl;delete t;}void deleter2(T *t) {cout << "deleter 2" << endl;delete t;}int main() {cout << "--------begin-----------" << endl;{cout << 1 << endl;shared_ptr<T> t1(new T, deleter1);cout << 2 << endl;shared_ptr<T> t2(new T, deleter2);cout << 3 << endl;shared_ptr<T> t3 = t2;cout << 4 << endl;t2 = t1;cout << 5 << endl;}cout << "--------end-----------" << endl;return 0;}
结果:
#include <iostream>#include <memory>using namespace std;class T {private:static int id;int tid;public:T() {tid = id++;cout << "id = " << tid << " constructor called" << endl;}~T() {cout << "id = " << tid << " destructor called" << endl;}};int T::id = 1;void deleter1(T *t) {cout << "deleter 1" << endl;delete t;}void deleter2(T *t) {cout << "deleter 2" << endl;delete t;}int main() {cout << "--------begin-----------" << endl;{cout << 1 << endl;T * trow = new T;shared_ptr<T> t1(nullptr, deleter1);cout << 2 << endl;shared_ptr<T> t2(nullptr, deleter2);cout << 3 << endl;t1.reset(trow);cout << 4 << endl;t2=t1;cout << 5 << endl;}cout << "--------end-----------" << endl;return 0;}

似乎是只会绑定对象最初被创建时的那个deleter,同时 reset() 方法有一个可以指定deleter的重载
