Effective C + + clause 13/14 managing resources with Objects | | Careful copying of behavior in resource management classes

Source: Internet
Author: User

III. Resource Management

The resource is that once you have used it, the system must be returned in the future. The most common resource in C + + is dynamic memory allocation. In fact, resources also include file descriptors, mutexes, glyphs in graphical interfaces, paint brushes, database connections, sockets, and so on.

1. Managing Resources with objects

void F ()

{

Investment *PLV = Createinvestment ();

There are a number of uncertainties, which may cause the following statements to be unenforceable, and there is a potential for resource leaks.

Delete PLV;

}

Here we put the resources into an object and then rely on the destructors inside the C + + itself to help us ensure that the resources are freed. Here to use the auto_ptr to solve. This is a class pointer object, known as a smart pointer. The destructor automatically calls delete.

    PINV1 point to Createinvestment () return;
     Std::auto_ptr<investment> pInv2 (PINV1);                      //Now PInv2 points to the object, while PINV1 is set to null;
     PINV1 = PInv2;                                                               Now PINV1 points to the object, and PIN2 is set to null;

Another problem is that multiple auto_ptr cannot point to an object at the same time. Another feature of Auto_ptr is that after copying, its raw object is set to null.

So, we refer to a reference counting type smart pointer shared_ptr. It can keep track of how many objects are pointing to a resource, and the resource is automatically deleted when no one points to it.

void F ()

{

std:: shared_ptr<investment> plv1 (Createinvestment ());//pinv1 point to Createinvestment () return;

std:: shared_ptr<investment> plv2 (PLV1);//pinv1,pinv2 points to the same object;

Plv1 = plv2;//Ibid., no change

The}//function exits, pinv1,pinv2 are destroyed, and the objects they refer to are automatically freed.

Another problem is that the above two smart pointers auto_ptr and shared_ptr only execute delete in the destructor instead of delete[], which means that the two pointers on a dynamically allocated array are also risky. This may require the use of boost:: Shared_array to help.

Remember:

To prevent resource leaks, use the Raii object, which obtains resources in the constructor and frees resources in the destructor.

The two more commonly used RAII classes are auto_ptr and shared_ptr. The latter is generally a better choice because copies are more intuitive.

2, in the resource management class carefully copy behavior

Resources requested on the heap we can use the above smart pointer class to manage, but some do not fit. At this point, we need to build our own resource management classes.

  void Lock (Mutex *pm);     //Lock the amount of mutex referred to by PM
  void unlock (Mutex *pm);        //To unlock PM
     The resource management classes that we build might be like this:
     Class
    {
        Public
        Explicit Lock (Mutex *pm)
        
        {
             Lock
        
        
        
             
        
        Private
        
    

What happens when the lock object is copied?

In general, we will choose the following two solutions:

1. Prohibit copying

2. Using the reference counting method for the underlying resource

Typically, the Raii class implements the "reference count" behavior whenever a TR1::SHARED_PTR member variable is included.
Class Lock
{
Public
Explicit Lock (Mutex *pm)
: Mutexptr (PM, unlock)//Because the TR1::SHARED_PTR default behavior is "when the reference count is 0 o'clock delete its referent", fortunately We can specify "reference count" as 9 o'clock called "unlock", that is, the second parameter
{
Lock (Mutexptr.get ());
}
Private
Std::tr1::shared_ptr<mutex> mutexptr;
};
In this case, the destructor is not explained because it is not necessary. The destructor that the compiler generates for us automatically calls its Non-static member variable (mutexptr) destructor. Mutexptr's destructor automatically calls the Tr1::shared_ptr (unlock) when the mutex reference count is 0.
Copying letters can be created automatically by the compiler, so you have to write them yourself unless the compiler builds the version you want to do.

Remember:

    • Copying a Raii object must replicate the resources it manages, so the copying behavior of the resource determines the copying behavior of the Raii object.
    • General and common RAII copy behavior is: suppress copy, execute reference counting method. But other behaviors may also be fulfilled.

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.