General smart pointers are initialized with a normal pointer, so it's easy to write the following code:
#include <iostream>
using namespace std;
intfunc1() {
// function that returns an integer
}
voidFunc2(autoptr<int*> ptr, int t) {
// Some operations
}
intmain() {
func2 ( autoptr< Span style= "Color:teal" > < int * > (new int< Span style= "Color:teal" > ( 5 )), func1 ());
// Other Operations
}
At first glance, this code seems to have no problems, but it is hidden.
When we call Func2, the arguments inside are required to operate, and there are three steps in the operation:
- int *t=new int (5);//Assuming the middle variable is t
- autoptr<int*> param (t);//Assuming the intermediate variable is param
- Func1 ();
We know that 11 will be called before 2, but the order of 3 calls is not necessarily.
Let's assume a situation where the call order is 1->3->2
Suppose we throw an exception when we call 3, when 1 has been called, that is, the memory has been allocated, but not successfully placed in the smart pointer. This block of memory is not automatically released. This causes a memory leak.
To avoid this situation, we can divide the process into two steps:
#include <iostream>
using namespace std;
intfunc1() {
// function that returns an integer
}
voidFunc2(autoptr<int*> ptr, int t) {
// Some operations
}
intmain() {
autoptr < int *> param (new int ( 5 ));
func2(param,func1());
// Other Operations
}
As long as you ensure that the initialization of the smart pointer is not interrupted, the vulnerability will naturally be lifted.
Even if Func1 throws an exception, when the smart pointer is initialized, the managed memory can be freed from the destructor.
EC Note: Part III: 17. Use a separate statement to put the Newed object into a smart pointer