shared_ptr
析构动作在创建时被捕获,这意味着
1. 虚析构不再是必须。
2. shared_ptr<void> 可以持有任何对象而且能够安全释放。比如
#include<iostream> #include<memory> using namespace std; class base : public enable_shared_from_this<base> { public: base(int n = 0) :x(n) {} int x; virtual void print() { cout << "self_shared:" << x << endl; } ~base() { cout << "this is base class" << endl; } }; class derive :public base { public: virtual void print() { cout << "derive" << endl; } ~derive() { cout << "this is derive class" << endl; } }; void test(const shared_ptr<base>& value1, const shared_ptr<base>& value2) { value1->print(); value2->print(); } int main() { shared_ptr<base> p1 = shared_ptr<derive>(new derive()); p1->print(); //shared_ptr<base> p1 = shared_ptr<base>(new base(22)); //p1->print(); //shared_ptr<base> sp = make_shared<base>(111); //sp->print(); //test(make_shared<base>(1), make_shared<base>(2)); return 0; }
输出
derive
this is derive class
this is base class
share_from_this()可以方便在类的内部获得自己的shared_ptr,比如以下代码:
class Stock { string key_; public: Stock(const string& k):key_(k){} const string& key() { return key_; } }; class StockFactory: public enable_shared_from_this<StockFactory> { map <string, weak_ptr<Stock>> stocks_; public: StockFactory() { cout << "the StockFactory is create" << endl; } ~StockFactory() { cout << "destory StockFactory!!!!" << endl; } shared_ptr<Stock> get(const string& key) { shared_ptr<Stock> pStock; weak_ptr<Stock>& wkStock = stocks_[key]; pStock = wkStock.lock(); if (!pStock) { pStock.reset(new Stock(key), std::bind(&StockFactory::deleteStock, shared_from_this(), std::placeholders::_1)); wkStock = pStock; } return pStock; } private: void deleteStock(Stock* stock) { if (stock) { cout << "deleteStock" << endl; stocks_.erase(stock->key()); } delete stock; } }; int main() { shared_ptr<Stock> p2; { shared_ptr<StockFactory> p1 = make_shared<StockFactory>(); p2 = p1->get("google"); cout << p1.use_count() << endl; } return 0; }
pStock.reset(new Stock(key), std::bind(&StockFactory::deleteStock, shared_from_this(), std::placeholders::_1));
如果在这一句中用this代替shared_from_this(),则最后智能指针p2的释放会出问题。因为p1已经销毁了,this指针是一个非法指针。但用shared_from_this(),这个指针所指对象的生命周期就和函数对象有关。