<effective c++> Reading digest--resource management< >

Source: Internet
Author: User

1. In addition to memory resources, other common resource include file descriptors, mutex locks, fonts and brushes in graphical user interfaces (G UIs), database connections, and network sockets. Regardless of the resource, it's important that it's being released when you're finished with it.

<item 13>use objects to manage resources

2, in fact, that's half the idea behind this item:by putting resources inside objects, we can rely on C + + ' s automatic dest Ructor invocation to make sure that the resources is released.

3. Many resources is dynamically allocated on the heap, is used only within a single block or function, and should be rel Eased when control leaves that block or function. The standard library ' s auto_ptr are tailor-made for this kind of situation. auto_ptr is a Pointer-like object (a smart pointer) whose destructor automatically calls delete on W Hat it points to. Here's how to use auto_ptr to prevent F' s potential resource leak:

classInvestment {...};//root class of hierarchy of//Investment Typesinvestment* createinvestment ();//return PTR to dynamically allocated//object in the investment hierarchy; //The caller must delete it//(parameters omitted for simplicity)voidF () {investment*PINV = Createinvestment ();//Call Factory function  ...                                            //Use PINV here may return earlier or throw an exception causing the delete Pinv   DeletePINV;//Release Object}voidf () {std::auto_ptr<Investment> PINV (Createinvestment ());//Call Factory//function  ...                                                  //Use PINV as//before}                                                      //automatically//Delete Pinv via//auto_ptr ' s dtor
Auto_ptr solves the security release problem after allocating an object on the stack (heap), and its presence stems from the support of C + + for exception. auto_ptr cannot exist in a container, multiple auto_ptr cannot share the same object's right to use, nor can it reference an array of objects and release them. It is deprecated to use auto_ptr, and it is recommended to use UNIQUE_PTR.

4. The above code example shows two important aspects of using object management resources

    • resources is acquired and immediately turned over to Resource-managing objects. 

      • in fact, the idea of using objects to manage Resources are often called resource acquisition is initialization (RAII), because it's so common To acquire a resource and initialize a Resource-managing object in the same statement. Sometimes acquired resources is assigned to resource-managing objects instead of initializing them, but either, every resource are immediately turned over to a Resource-managing object at the time of the resource is Acquired.

    • resource-managing objects use their destructors to ensure Resources is released. 

      •  things can get tricky when the act of Rele Asing resources can leads to exceptions being thrown, but that's a matter addressed by Item 8, so we'll not worry about it here.

5, Because an auto_ptr automatically deletes what it points to when the auto_ptr is destroyed, it's Impor Tant that there never is more than one auto_ptr pointing to an object. If there were, the object would is deleted more than once, and that would put your program on the fast track to undefined Behavior. To prevent such problems, auto_ptrS has an unusual characteristic:copying them (via copy constructor or copy as Signment operator) sets them to NULL, and the copying pointer assumes sole ownership of the resource! STL containers require that their contents exhibit "normal" copying behavior, so containers of auto_ptr aren ' t al lowed.

Std::auto_ptr<investment>//PInv1 points to thepInv1 (Createinvestment ()); //object returned from//createinvestmentstd::auto_ptr<Investment> pInv2 (PINV1);//PInv2 now points to the//object; pInv1 is now nullPINV1= PInv2;//Now pInv1 points to the//object, and pInv2 is null

6, an alternative- auto_ptr is a reference-counting smart pointer (RCSP). An RCSP is a smart pointer so keeps track of what many objects point to a particular resource and automatically deletes T He resource when nobody was pointing to it any longer. As such, Rcsps offer behavior this is similar to that of garbage collection. Unlike garbage collection, however, Rcsps can ' t break cycles of references (e.g., and otherwise unused objects to one another).

TR1 's tr1::shared_ptr (see Item Wu) is a RCSP, so you could write F the This by:

void f () {  ...  Std::tr1::shared_ptr<Investment>    PINV (Createinvestment ());              // Call Factory function

... // Use PINV as before } // automatically delete // PINV via shared_ptr ' s dtor

tr1::shared_ptr is similar in usage to auto_ptr , but the performance is different from auto_ptr when assigned.

voidf () {... std::tr1::shared_ptr<Investment>//PInv1 points to thePINV1 (Createinvestment ());//object returned from//createinvestmentstd::tr1::shared_ptr<Investment>//both PINV1 and PInv2 nowPInv2 (PINV1);//Point to the objectPINV1= PInv2;//ditto-nothing has//changed  ...} //PInv1 and PInv2 are//destroyed, and the//Object They point to IS//automatically deleted

Because copying tr1::shared_ptrs Works "As expected," they can used in STL containers and other contexts where auto_ptr' s unorthodox copying behavior is inappropriate.

7, Both auto_ptr and tr1::shared_ptr use delete in their destructors, not delete []. (Item describes the difference.) That means this using auto_ptr or tr1::shared_ptr with dynamically allocated arrays are a bad idea, tho Ugh, regrettably, one that'll compile:

 std::auto_ptr<std::string  > //  bad idea! the wrong   APs ( new  std::string  [10 ]); //  Delete form would be used  std::tr1::shared_ptr  <int  > SPI ( Span style= "color: #0000ff;"    >new  int  [1024 ]); //  same problem  

There is no smart pointer to an array in the C + + standard library, nor is there a vector or string instead of an array in TR1. If you still think it would is nice to has auto_ptr-and tr1::shared_ptr-like classes for arrays, look To Boost (see Item 55). There you'll be pleased to find the boost::scoped_array and Boost::shared_array classes This offer the B Ehavior You "re looking for.

8, things to Remember

    • To prevent resource leaks, use RAII objects. Acquire resources in their constructors and release them in their destruc Tors.

    • Commonly useful RAII classes is tr1::shared_ptr and auto_ptr. tr1::shared_ptr is usually the better choice, because it behavior when copied is intuitive. Copying an auto_ptr sets it to null.  

<item 14>think carefully about copying behavior in resource-managing classes.

9, what should happen if an RAII object is copied? Most of the time, you'll want to choose one of the following possibilities:

class Lock {public:  explicit Lock (Mutex *pm)  : mutexptr (PM)   Lock (MUTEXPTR); }                          //  Acquire resource  ~lock () {unlock (mutexptr);}                // Release Resource
Private : *mutexptr;};

    • Prohibit copying

      • In many cases, it makes no sense to allow RAII objects to be copied. This is likely to being true for a class like Lock, because it rarely makes sense to has "copies" of Synchronizatio N Primitives. The reference ITEM6 is implemented as follows

class Private uncopyable {            //  prohibit copying-seepublic:                                     //  Item 6  ... c10/>// as before};

    • Reference-count the underlying resource.

      • Sometimes it's desirable to a resource until, the last object using it had been destroyed. When that's the case, copying a RAII object should increment the count of the number of objects referring to the resource . This is the meaning of ' copy ' used by tr1::shared_ptr. Fortunately, TR1::SHARED_PTR allows specification of a "deleter"-a function or function object to being called when the ref Erence count goes to zero. (This functionality does is exist for auto_ptr and which always deletes its pointer.) The deleter is a optional second parameter to the Tr1::shared_ptr constructor and so the code would look like this

classLock { Public:  ExplicitLock (Mutex *pm)//Init shared_ptr with the Mutex: Mutexptr (PM, unlock)//To point to and the unlock func  {                              //As the deleter    Lock(Mutexptr.Get());//See Item in "get" for info  }Private: Std::tr1::shared_ptr<Mutex> mutexptr;//Use shared_ptr}; //instead of raw pointer

      • In this example, notice how the Lock class no longer declares a destructor. That's because there ' s no need to. Item 5 explains that a class ' s destructor (regardless of whether it's compiler-generated or user-defined) automatically I Nvokes the destructors of the class ' s non-static data members. It is best to add a comment stating that you are not forgetting to release the lock resource in a destructor.
    • Copy the underlying resource.

      • That's, copying a Resource-managing object performs a "deep copy."

    • Transfer ownership of the underlying resource

10, things to Remember

    • Copying an RAII object entails Copying The resource it manages, so the Copying behavior of the resource determines the COP Ying behavior of the RAII object.

    • Common RAII class Copying behaviors is disallowing copying and performing reference counting, but other behaviors is POS Sible.

<effective c++> Reading digest--resource management< >

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.