//
A simple example of preventing memory leaks
//
voidTest () {//managing resources with RAII features//When the smart pointer unique_ptr is destroyed, the object it points to is also destroyed//here, after the test function returns, p will automatically destroy//unique_ptr<int[]> P (new int[200]); //Generate resources directly//when the test function returns p cannot be destroyed normally, it will cause a resource leak.//int* p = new int[200];}intMain () { while(1) {test (); Sleep (1 ); } return 0;}
1//[Smart pointer] action test2 3//######################################################################################################4//# "Unique_ptr"5unique_ptr<string>Unique_ptr__fn () {6 //"Unique_ptr"7 //is a smart pointer that can only point to one object at a time and cannot be copied and assigned8unique_ptr<string> A (New string("Test") );//new out a string and use ' smart pointer (a) ' to point to it9*a ="What ?";//modifies the value of the string pointed to by pointer aTen //unique_ptr<string> B (a); //error, cannot be copied One //unique_ptr<string> C = A; //error, cannot be assigned Aunique_ptr<string> D (A.release ());//You can call release () to free the pointer to transfer ownership, note: The object pointed at this time is not destroyed -cout << *D; - //D.reset (); //manually call reset to destroy the object pointed to the //cout << *d; //error, the object pointed to has been manually destroyed - -unique_ptr<string> e = Move (d);//UNIQUE_PTR Support Move () Note the move construct exists in the UNIQUE_PTR
So can also be used as a return value - //cout << *d; //error, Pointer D has moved to E + - returnE//return smart pointer e + } A at voidtest_unqiue_ptr () { -unique_ptr<string> f = unique_ptr__fn ();//at this point f = Move (e); -cout << *F; - } - - in - to//###################################################################################################### +//# "shared_ptr" - voidSHARED_PTR__FN (shared_ptr<string>&x) { the //"Shared_ptr_test" * //Smart pointer with reference count, so the assignment is allowed with the copy operation, and only the object that is pointed to is destroyed when the count is 0 o'clock $ //so it seems that shared_ptr can replace unique_ptr without considering efficiency.Panax Notoginseng //but for a resource that does not need to be shared, try to use Unique_ptr -shared_ptr<string> A (x);//Copy Construction OK thecout << *A; + //shared_ptr<string> B = A; //Copy Construction OK A //shared_ptr<string> C; the //C = b; //Assignment Operation OK + - return;//The local pointer a will be invalidated after RET, but the pointed object will not be destroyed $ } $ - voidshared_ptr_test () { -shared_ptr<string> x (New string("Test") );//construct a shared_ptr theSHARED_PTR__FN (x);//Pass pointer x to the next function - Wuyi return;//the object will be destroyed after RET the}
Using smart pointers to manage objects (based on RAII)