Smart pointers are a way of using the RAII mechanism (explained later) in C + + to manage pointers through objects.
In C + +, dynamic memory needs to be maintained by ourselves, we must release it manually before the function scope or program exits abnormally , otherwise it will cause a memory leak.
For example: When we use pointer variables to create an object, we need to manually delete it
String * pstr = new string ("Hello world!"); .... delete Pstr;
In fact, even though we are very cautious, there are times when things can still make us impossible:
Case one: Within a branch of the program, forget to free memory void FunTest1 () {int *parr = new INT[10]; file* pFile = fopen ("Test.txt", "R"), if (pfile==null) {return;} ...//Handling other code//.....if (parr!=null) {delete[] Parr;parr = NULL;}}
Scenario Two: When the program throws an exception, forget to release memory void FunTest2 () {int *parr = new int[10];try{//...//other code//...} catch (...) {return;} if (parr!=null) {delete[] Parr;parr = NULL;}}
Each time the dynamic development of memory, you have to manually release, a bit inattentive, will cause a memory leak. (Code a lot, logic a complex, scared I dare not to dynamically open up memory!)
Then, I naturally foolishly expected: if there is something to manage the pointer, let it in the function scope or before the end of the automatic release of memory, it is not flattered?
Therefore, we introduce RAII (resource acquisition is initialization) mechanism: through the class to encapsulate pointers, in the constructor to complete the initialization of resources, in the destructor to complete the cleanup of resources and Shanwei work.
Want to know how to funeral, and listen to tell: Smart pointer detailed auto_ptr
"C + +" smart pointer in detail (a): The introduction of smart pointers