shared_ptr Here's a-reference number smart pointer that you can't find in the standard library. Most people should have experienced the use of smart pointers, and there are already many articles about the number of citations. The most important detail is how the reference number is executed-insert, meaning that you add the function of the reference count to the class, or a non-insertion, meaning that you do not do so. Boost shared_ptr is a non-insertion type, and this implementation uses a reference counter that is allocated from the heap. There is a lot of discussion about providing a parametric strategy that is very suitable for any situation, but the result of the final discussion is to decide against focusing on usability. But don't expect the outcome of the discussion to be over. SHARED_PTR does what you want: he is responsible for removing the object it points to (pointee) while not using the instance, and it is free to share the object it points to (pointee).
| 123456789101112131415161718192021222324252627282930 |
voidPrintIfString?(constany&Any){if(cons tshared_ptr* s=any_cast>(&Any)){cout<<**s<<endl;}}intmain(intargc,char* argv[]){std::vectorStuff;shared_ptrSharedString1?(newstring("Shareme.Bytheway,Boost.anyisanotherusefulBoostlibrary"));shared_ptrSharedString2?(SharedString1?);shared_ptrSharedInt1?(newint(42));shared_ptrSharedInt2?(SharedInt1?);Stuff.push_back(SharedString1?);Stuff.push_back(SharedString2?);Stuff.push_back(SharedInt1?);Stuff.push_back(SharedInt2?);//Printthestringsfor_each(Stuff.begin(),Stuff.end(),PrintIfString?);Stuff.clear();//Thepointeesoftheshared_ptr‘s//willbereleasedonleavingscope//shared_ptr的pointee离开这个范围后将被释放return0;} |
What do you mean smart pointers? Introduction to Smart pointers.
Smart pointer (smart pointer) is a class that stores pointers to dynamically allocated (heap) objects and is used for lifetime control to ensure that dynamically allocated objects are destroyed automatically and correctly to prevent memory leaks. One of its common implementation techniques is the use of references.
C + + smart pointer shared_ptr