Clause 13: object-oriented resource management

Source: Internet
Author: User

The so-called resource is that once you use it, you must remember to return it to the system. If this is not done, resources will be wasted. Resources here refer not only to memory, but also to file descriptors, mutex locks, database connections...

These terms are a direct and easy-to-understand object-based resource management method built on the C ++ constructor, destructor, and copy functions. Experience shows that after training, strict adherence to these practices can almost eliminate resource management problems. Next we will start ~~~~~

 

First, let's start with the factory model:

Assume that we useProgramLibrary, among which various investment types inherit from a root class investment;

Classinvestment {};

Further, we assume that this library supplies a specific investor object through a factory function:

Investment * createinvestment () {} // returns a pointer to the dynamically allocated object in the investment inheritance system. The caller has the responsibility to delete it. To simplify it, no parameters are written.

 

Now, an F function is considered to fulfill this responsibility:

Voidf (){

Investment * pinv = createinvestment ();

...

Deletepinv;

}

This seems pretty good, but unfortunately something happened, and it happened in "..."CodeMay be return or an exception. In short, it is not executed on the Delete. We leak not only memory blocks, but also any resources stored by investment objects.

 

The problem now is that pinve and delete are not in the same object. If they are in the same object, we can analyze the structure by the object's destructor. So ........

We can use the auto_ptr provided by the standard library. This is a class pointer object. That is, the so-called smart pointer. The Destructor automatically calls delete for the object.

Voidf (){

STD: auto_ptr <investment> pinv (createinvestment ());

...

}

 

This simple example demonstrates two key ideas of "Object-based resource management:

L after obtaining the resource, immediately put it into the management object.

In the above Code, the resources returned by createinvestment are treated as the initial values of the Manager auto_ptr. In fact, the concept of "Object-based resource management" is often referred to as "Resource Access time is the initialization time" (resource acquisition is initializatioin, raiI ).

L management objects use destructor to ensure resources are released.

 

Because auto_ptr is automatically deleted when it is destroyed, be sure not to let multiple auto_ptr point to the same object at the same time. If so, the object will be deleted more than once, leading to undefined behavior. To prevent this problem, auto_ptr has an unusual nature: if you copy them through the copy function, they will become null, And the pointer obtained by the copy function will obtain the unique ownership of the resource. As follows:

STD: auto_ptr <investment> pinv (createinvestment (); // pinv point to a investment OBJ

STD: auto_ptr <investment> pinv2 (pinv); // pinv2 point to OBJ, pinv is null

Pinv = pinv2 (); // pinv piont to OBJ, pinv2 is null

This strange replication behavior adds the underlying disorder: "The resources managed by auto_ptr must not have more than one auto_ptr pointing to it at the same time ". However, in STL, the container requires its elements to perform "normal" replication, so these containers cannot be auto_ptr.

 

An alternative to auto_ptr is reference-counting smart pointer (rcsp )". Rcsp is also a smart pointer. Continuously track the total number of objects pointing to a resource and automatically delete the resource when no one points to it.

Voidf ()

{

STD: tr1: shared_ptr <investment> pinv1 (createinvestment (); // pinv1 point to a investment OBJ

STD: tr1: shared_ptr <investment> pinv2 (pinv1); // pinv1 and pinv2 point to the same OBJ;

Pinv1 = pinv2; // pinv1 and pinv2 point to the same OBJ;

}

 

Both auto_ptr and TRL: shared_ptr perform the delete rather than Delete [] action in their destructor. That means using auto_ptr and TRL: shared_ptr on the array obtained by dynamic allocation is a bad idea.

 

Remember:

L to prevent resource leakage, use raiI objects. They obtain resources in the constructor and release resources in the destructor.

L two commonly used raiI classes are auto_ptr and TRL: shared_ptr. The latter is a better choice. Because of its intuitive copy behavior. If the former option is selected, the copy action points to null.

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.