For the exception section, there will be an overall article (still a little bit down ), a short statement is used to describe the essence of each section of the exception section. The entire section involves many tests. Each test contains an article corresponding to each section. This article focuses on how to use local objects to manage resources in section 9th.
Thoughts:
Partial object management resources. When an exception occurs during a call, use the policy that must be called for partial object destructor to release resources in the destructor.
A local object stores [resources that must be automatically returned] and returns resources using the object's destructor. Auto_ptr, scoped_ptr, auto_lock, FilePtr, and HandlePtr are all of these ideas.
This is the sample code.
# Include <iostream> # include <time. h ># include <memory> using namespace std;/* Author: lpstudy Date: Content: more effective C ++ exception chapter 9th, use the partial object destructor to release resources to ensure that resources are safely released when exceptions occur. */# Define TRACE_FUCTION_AND_LINE (fmt ,...) printf ("[% 20 s: % 4d]" fmt "\ n" ,__ FUNCTION __, _ LINE __, ##__ VA_ARGS __) // Widget is just a simple test class and serves as an instantiation parameter of the auto_ptr template. Auto_ptr manages the new Widget memory and is responsible for deleteclass Widget {public: Widget (int nHight = 0): m_nHight (nHight) {TRACE_FUCTION_AND_LINE ();}~ Widget () {TRACE_FUCTION_AND_LINE ();} void Log () {TRACE_FUCTION_AND_LINE ("My Log ------ % d", m_nHight);} int m_nHight ;}; // FilePtr receives a FILE handle and closes the handle when the object is parsed. Class FilePtr {public: explicit FilePtr (FILE * f = NULL): m_hFile (f) {TRACE_FUCTION_AND_LINE ("m_hFile: % 08 p", m_hFile );}~ FilePtr () {if (m_hFile) {TRACE_FUCTION_AND_LINE ("close m_hFile: % 08 p", m_hFile); fclose (m_hFile) ;}} FILE * Get () {return m_hFile ;} private: FILE * m_hFile;}; int main () {TRACE_FUCTION_AND_LINE ("Trace auto_ptr ....... "); auto_ptr <Widget> autoWight (new Widget (100); autoWight-> Log (); TRACE_FUCTION_AND_LINE (" Trace FilePtr ....... "); FilePtr filePtr (fopen (" data.txt "," a + "); char buf [100] =" Data Test... \ n "; fwrite (buf, 1, strlen (buf), filePtr. get (); return 0 ;}
I hope that this idea has not been obtained, or I know it, but I have not fully understood it. Let's take a closer look at this simple example.
If you want to learn more about auto_ptr and lock, we recommend that you read scoped_ptr and autolock.
Believe me, this is very valuable. Google Code blockbuster use.