Effective C++ .13使用智能指针来引用资源
#include <iostream> #include <cstdlib> #include <memory> using namespace std; class Kiwi { private: int weight; public: Kiwi(int w) : weight(w) {} ~Kiwi() { cout<<"~Kiwi"<<endl; } int getWeight() {return weight;} }; void driven() { shared_ptr<Kiwi> p(new Kiwi(100)); cout<<p->getWeight()<<endl; shared_ptr<Kiwi> q = p; cout<<p->getWeight()<<endl; cout<<q->getWeight()<<endl; } int main() { cout<<"test start"<<endl; driven(); cout<<"test end"<<endl; return 0; }
auto_ptr同时只能有一个指向资源
shared_ptr同时可以有多个指向资源