Smart pointers std::auto_ptr and shared_ptr

Source: Internet
Author: User

It is important to note that the Auto_ptr class can be used to manageNewallocation of a single object, but the dynamically allocated array cannot be managed (we usually do not use arrays, but instead of arrays using vectors). Auto_ptr have unusual behavior when copying and assigning values, so auto_ptrs cannot be stored in the STL container. When auto_ptr leaves its scope or is destroyed, the objects managed by Auto_ptr are destroyed. Header file required for use with Std::auto_ptr: #include<memory>//Example 1 (b): Security code, using Auto_ptr   voidf () {auto_ptr<T> PT (NewT); ..... } //Cool: The destructor is called when the PT is out of scope, so the object is automatically deletedThe code now does not leak objects of type T, whether the function exits gracefully or throws an exception, because the PT destructor is always called at the time of the stack.  The cleanup will be done automatically.   Finally, using a auto_ptr is as easy as using a built-in pointer, and if you want to "undo" the Resource and take the manual ownership again, we just call release (). //Example 2: Using a auto_ptr     voidg () {T* Pt1 =NewT//now, we have a well-distributed object .Auto_ptr<t> Auto_pt2 (PT1);//the ownership was passed to a Auto_ptr object, Auto_pt2 pointed to the pt1//use auto_ptr just like we used to use a simple pointerAuto_pt2 = A;//just like "*PT1 = n"Auto_pt2->somefunc ();//just like "Pt1->somefunc ();" //use Get () to get the value of the pointerASSERT (pt1 = = Auto_pt2.Get() );//The same//using release () to revoke ownership, AUTO_PT2 the saved pointer address to PT3, which points to null. t* PT3 = Auto_pt2.release ();//     //Delete This object yourself, because now there is no auto_ptr owning this object     DeletePT3; } //Pt2 no longer has any pointers, so don't try to delete them ... ok, do not repeat deleteFinally, we can use Auto_ptr's reset () function to reset the auto_ptr to have another object. If the auto_ptr already has an object, it will first delete the object already owned, so calling Reset () is like destroying the auto_ptr, and then creating a new one and owning the object://Example 3: Using Reset ()//     voidh () {auto_ptr<T> PT (NewT1) ); Pt.reset (NewT2) );//that is, the PT will first delete the address that PT is currently pointing to (new T (1) to get the address),//and then point to the address assigned to new T (2)}//Finally, the PT is out of scope,//the second t is also automatically deleted.while the Boost smart pointer--shared_ptrboost::scoped_ptr is easy to use, its inability to share ownership has greatly limited its scope, and boost::shared_ptr can address this limitation. As the name implies, Boost::shared_ptr is a smart pointer that can share ownership, let's start with an example to see its basic usage: #include<string>#include<iostream>#include<boost/shared_ptr.hpp>classimplementation{ Public:    ~implementation () {std::cout <<"destroying implementation\n"; } voidDo_something () {std::cout <<"Did something\n"; }};voidTest () {boost::shared_ptr<implementation> SP1 (Newimplementation ()); Std::cout<<"The Sample now has"<<sp1.use_count () <<"references\n"; Boost::shared_ptr<implementation> SP2 =SP1; Std::cout<<"The Sample now has"<<sp2.use_count () <<"references\n";    Sp1.reset (); Std::cout<<"After Reset SP1. The Sample now has"<<sp2.use_count () <<"references\n";    Sp2.reset (); Std::cout<<"After Reset sp2.\n";}voidMain () {test ();} The output of the program is as follows: The Sample now has1referencesthe Sample now have2referencesafter Reset SP1. The Sample now has1   referencesdestroying Implementationafter Reset SP2. As you can see, boost::shared_ The PTR pointer SP1 and SP2 both have access to the implementation object, and the memory of the object it manages is automatically freed when both SP1 and SP2 release ownership of the object. The access rights of the shared object also enable automatic management of its memory. BOOST::SHARED_PTR memory management mechanism: BOOST::SHARED_PTR management mechanism is not complex, is to manage the object of the reference count, when a new boost::shared_ptr to manage the object, Adds one to the reference count of the object, reduces the reference count of the object by one when it is managed by one boost::shared_ptr, and if the reference count of the object is 0, it means that no pointer is administered to it, and then the delete is called to release the memory it occupies. The above example can be illustrated as follows: SP1 the implementation object is managed, its reference count is 1 increased SP2 the implementation object is managed, its reference count is increased to 2SP1 release the implementation object to be managed, Its reference count becomes 1SP2 released to manage the implementation object, its reference count becomes 0, and the object is automatically removed Boost::shared_ptr features: Compared to the boost::scoped_ptr described earlier, boost: SHARED_PTR can share ownership of an object, so its scope of use is largely limited (there are some usage rules that need to be followed, described below), and it can also be used in STL containers. It's also thread-safe, which is also important in multithreaded programs. BOOST::SHARED_PTR rules: Boost::shared_ptr is not absolutely secure, the following rules will make it safer to use boost::shared_ptr: Avoid shared_ The direct memory management operation of the object managed by PTR, so as not to cause the object to be re-released shared_ptr does not automatically manage the object memory that is referenced by a circular reference (this is a common problem with various other reference count management memory methods). Do not construct a temporary shared_ptr as a function parameter. The following code can cause a memory leak: voidTest () {foo (boost::shared_ptr<implementation> (Newimplementation ()), G ());} The correct usage is:voidTest () {boost::shared_ptr<implementation> SP (Newimplementation ()); Foo (sp,g ());}
Reprinted from: http://blog.163.com/[email protected]/blog/static/70234777201061465831662/

Smart pointers std::auto_ptr and shared_ptr

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.