(vi) The memory management shared_ptr of the boost library

Source: Internet
Author: User

(vi) The memory management shared_ptr of the boost library1. Basic usage of shared_ptr
    boost::shared_ptr<int> SP (int.);     //A pointer to an integer shared_ptr  
    ASSERT (Sp.unique ());                        //Now shared_ptr is the only holder of the pointer
    boost::shared_ptr<int> SP2 = SP;            //second shared_ptr, copy constructor 
    2);   //Two shared_ptr equal, point to the same object, reference count is 2
    100;                                 
    );                         //Another shared_ptr has been modified at the same time
    Sp.reset ();                                 //Stop shared_ptr use, reference count minus one
    ASSERT (!SP);                                //SP no longer holds any pointers (null pointers)
    1);               //SP2 Reference count becomes 1
    Sp.reset (Int ());                      //SP managing a new object  
    20);

2, used in standard containers

There are two ways to apply shared_ptr to standard containers (or other containers such as container adapters).

One usage is to use the container as an object of shared_ptr management, such as shared_ptr<list<t>, so that the container can be safely shared, and the usage is no different from the normal shared_ptr, we will not discuss it.

Another usage is to use shared_ptr as a container element, such as vector<shared_ptr<t>, because shared_ptr supports copy semantics and comparison operations, conforms to the requirements of the standard container for elements, Therefore, it is possible to implement a pointer to the element safely in the container instead of a copy.

Standard containers do not accommodate auto_ptr, which is specifically defined by the C + + standard (readers should never have this idea). Standard containers also cannot accommodate scoped_ptr because Scoped_ptr cannot copy and assign values. The standard container can hold the raw pointer, but this loses many of the benefits of the container, because the standard container cannot automatically manage elements of the type pointer, and you must write extra large amounts of code to ensure that pointers are eventually deleted correctly, which is often cumbersome and difficult to implement.

The container that stores the shared_ptr is almost the same as the container that stores the original pointer, but SHARED_PTR provides the programmer with pointers to the management of the shared_ptr without worrying about resource leaks.

intmain()   
{      
    typedef vector<shared_ptr<int> > vs;    //A standard container type      that holds shared_ptr 
    VS V (Ten);                               //Declare a container with 10 elements initialized to a null pointer       
    int i = 0;      
    For (vs::iterator pos = V.begin (); pos! = V.end (); ++pos      )
    {          
        (*pos) = make_shared<int> (++i);     //Use factory functions to assign          values  
        cout << * (*pos) << "";            //Output      value 
    }      
    cout << Endl;       
    shared_ptr<int> P = v[9];       
    *p = 100;      
    cout << *v[9] << Endl;  

This code needs to be aware of the use of iterators and operator[], because the container is stored in shared_ptr, we must use the dereference operator * for the iterator Pos to obtain the shared_ptr, and then use the dereference operator for shared_ptr * To manipulate the true value. * (*pos) can also be written directly **pos, but the former is clearer, the latter is easy to confuse people. Vector's operator[] usage is similar to iterators and requires the use of * to get real values.

3. Using Assistant class Enable_shared_from_this

Why use Enable_shared_from_this, perhaps you are confused about this class, first look at the following situation:

Class MyPoint
{
Public
    MyPoint () {std::"mypointStd::endl;}   
    ~mypoint () {std::"~mypointStd::endl;}   
    function that returns this
    Boost::shared_ptr<mypoint> getpoint ()
    {
        Return boost::shared_ptr<mypoint> (this);   //error, a new reference count will be returned  
    }
};
int _tmain (int argc, _tchar* argv[])
{
    Boost::shared_ptr<mypoint> p1 (new mypoint);     
    Boost::
    std::",//Output reference count condition  
    P1.reset ();          //Memory will be released
}

The answers we get will be:

MyPoint
The
~mypoint

How to return this correctly, then need to use enable_shared_from_this, the reason for introducing enable_shared_from_this is that you can implement the return value to point to the class itself shared_ptr

The correct wording should be this:

Public boost::enable_shared_from_this<mypoint>
{
Public
    MyPoint () {std::"mypointStd::endl;}   
    ~mypoint () {std::"~mypointStd::endl;}   
    function that returns this
    Boost::shared_ptr<mypoint> getpoint ()
    {
        return Shared_from_this ();
    }
};
int _tmain (int argc, _tchar* argv[])
{
     Boost::shared_ptr<mypoint> p1 (new mypoint);     
     Boost::
     std::",//Output reference count condition  
     P1.reset ();          //Memory will be released
}
4. Custom-made remove device

When you are programming with Windows API functions, perhaps the most annoying thing you can do is to ensure that the kernel object you are applying is closed, and consider the code:

    int *p = (sizeof (p));
    Business Processing
    //......
    0, p);

The object cannot be deleted through delete, but a release function, the answer is yes, shared_ptr.

    int *p = (sizeof (p));
    Lambda expressions are used here and require vs2010 or later support
    Boost::shared_ptr<int> ptr (P, [] (0, p);});  
5. Integrated Application Example

The following implements a thread class that cleans up its own memory at the end of its run

#include <set>
#include <Windows.h>
#include <boost/thread.hpp>
class myself;
std::set< Boost::shared_ptr<myself> > myList; 
Boost::thread *ptrth;
Public boost::enable_shared_from_this<myself>
{
Public
    Myself ()
    {
        printf ("myself\n");  
    }
    voidstartthread() 
    {
        Start a thread    
        this);
    }
    voidRun() 
    {
        Thread Task functions
        Sleep (the);
        printf ("stop thread\n");  
        Stop ();
    }
    voidStop() 
    {
        Delete yourself
        Mylist.erase (Shared_from_this ());
    }
    ~myself ()
    {
        printf ("~myself\n");  
    }
};
voidtestshareptr() 
{
    Boost::shared_ptr<myself> ptr1 (new myself); 
    Save to List
    Mylist.insert (PTR1);
    Ptr1->startthread ();
}

(vi) The memory management shared_ptr of the boost library

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.