// (C) Porkolab 2003 // // A.5.6. // // Resource allocation problems // is this correct? void f() { char *cp = new char[1024]; g(cp); h(cp); delete [] cp; } // is this nice? void f() { char *cp = new char[1024]; try { g(cp); h(cp); delete [] cp; } catch( ... ) { delete [] cp; throw; } } // Stroustrup: resource allocation is initialization struct Res { Res(int n) { cp = new char[n]; } ~Res() { delete [] cp; } char *getcp() const { return cp; } }; void f() { Res res(1024); g(res.getcp()); h(res.getcp()); } // But be care: struct BadRes { Res(int n) { cp = new char[n]; ... throw n; ... } ~Res() { delete [] cp; } ... };