Clause 13: manage resources by object.
A.Resource leakage:
#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;}
(No destructor is called, and resources are not released in the heap)
B.Use objects to manage resources:
Template <typename T> class resource_ptr/* adds the management type 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 ;}
(Use an object to call the destructor to release resources through delete)
3. Resource Management (Terms: 13-17)