条款13: 以对象管理资源。
a. 资源泄露:
#include <iostream> using namespace std; struct INT { int v; INT(int x) : v(x) { cout << "INT constructor called." << endl; } ~INT() { cout << "INT deconstructor called." << endl; } }; int main() { INT *tmp = new INT(6); cout << (*tmp).v << endl; cout << tmp->v << endl; }
(没有调用析构函数,资源在堆中没有释放)
b. 用对象管理资源:
template<typename T> class Resource_ptr /* 加入管理类型 Resource_ptr */ { public: Resource_ptr (T *p = NULL) : r_ptr(p) { cout << "Resource_ptr constructor called;" << endl; } ~Resource_ptr () { cout << "Resource_ptr deconstructor called; " << endl; if(r_ptr) delete r_ptr; } const T& operator* () const { return *r_ptr; } T& operator* () { return *r_ptr; } const T* operator-> () const { return r_ptr; } T* operator-> () { return r_ptr; } /*T* get() { return r_ptr; }*/ private: T *r_ptr; }; typedef Resource_ptr<INT> R_ptr; int main() { /*INT *tmp = new INT(6);*/ R_ptr tmp = R_ptr(new INT(6)); cout << (*tmp).v << endl; cout << tmp->v << endl; }
(利用对象,通过 delete 调用析构函数释放资源)