Today let's analyze the smart pointers and exceptions in C + +, first of all, to popularize the concept first!
(1) Smart pointers: Intelligent or automated management pointers to the release of dynamic resources.
(2) exception: When a function discovers an error that it cannot handle, let the caller of the function handle the problem directly or indirectly.
(3)RAII: resource allocation is initialized. The constructor completes the initialization of the object, and the destructor completes the cleanup of the object, rather than deleting it.
In the actual code process, we can easily write out the exception of the code, do not believe to see the following examples:
void Test () {int *p = new int (1); if (1) {return;} Delete p;}
It is easy to see that in the IF statement has returned, then the code will not be executed, so there is a risk of memory leaks, which is very scary, it may run out of memory, not only the current program will crash, serious system will crash, this is to see what you do, haha. Then
, someone must have thought that there is no exception in C + + capture it? Yes, in order to increase the compatibility of the code, C + + uses the following code to catch exceptions:
throw throws an exception; try{//code}catch (Exception type) {//After an exception occurred}
Does the above code do the work?
void Test () {int *p = new int (1); Try{if (1) {throw 1;}} catch (int e) {delete p;throw;} Delete p;}
But there are two exceptions thrown in the catch, which is very confusing to manage. So the introduction of smart pointers, it is more convenient to solve the exception. The raii mentioned above is the key idea for writing exception-safe code.
Let's introduce the smart pointers in the boost library.
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/7E/7F/wKiom1cCUyvhh06nAAAwJEfwWVA127.png "title=" capture. PNG "alt=" Wkiom1ccuyvhh06naaawjefwwva127.png "/>
This article is from the "stand out or Get out" blog, so be sure to keep this source http://jiazhenzhen.blog.51cto.com/10781724/1760193
Smart pointers and exceptions