C++ Chapter 3. Resource Management

本文深入探讨了智能资源管理的关键概念与实践,包括自动指针、引用计数智能指针、RAII原则下的资源管理策略,以及如何避免资源泄露等问题。通过实例解析,指导开发者实现资源的有效管理,确保程序的稳定性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Many resources are dynamically allocated on the heap, are used only within a single block or function, and should be released when control leaves that block or function. The standard library'sauto_ptr is tailor-made for this kind of situation. auto_ptr is a pointer-like object (asmart pointer) whose destructor automatically callsdelete on what it points to. 

std::auto_ptr<Investment> pInv(createInvestment());  

Because an auto_ptr automatically deletes what it points to when theauto_ptr is destroyed, it's important that there never be more than oneauto_ptr pointing to an object. If there were, the object would be deleted more than once, and that would put your program on the fast track to undefined behavior. To prevent such problems,auto_ptrs have an unusual characteristic: copying them (via copy constructor or copy assignment operator) sets them to null, and the copying pointer assumes sole ownership of the resource!

std::auto_ptr<Investment>                 // pInv1 points to the

  pInv1(createInvestment());              // object returned from

                                          // createInvestment



std::auto_ptr<Investment> pInv2(pInv1);   // pInv2 now points to the

                                          // object; pInv1 is now null



pInv1 = pInv2;                            // now pInv1 points to the

                                          // object, and pInv2 is null

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

Both auto_ptr and tr1::shared_ptr use delete in their destructors, notdelete []. (Item 16 describes the difference.) That means that usingauto_ptr orTR1::shared_ptr with dynamically allocated arrays is a bad idea, though, regrettably, one that will compile:

std::auto_ptr<std::string>                       // bad idea! the wrong

  aps(new std::string[10]);                      // delete form will be used



std::tr1::shared_ptr<int> spi(new int[1024]);    // same problem

  • Common RAII class copying behaviors are disallowing copying and performing reference counting, but other behaviors are possible

such as 

disallowing copying

class Lock: private Uncopyable {            // prohibit copying — see

public:                                     // Item 6



 ...                                        // as before



};

performing reference counting

class Lock {

public:

  explicit Lock(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 15 for info on "get"

  }

private:

  std::tr1::shared_ptr<Mutex> mutexPtr;    // use shared_ptr

};                                         // instead of raw pointer

  • Copy the underlying resource. Sometimes you can have as many copies of a resource as you like, and the only reason you need a resource-managing class is to make sure that each copy is released when you're done with it. In that case, copying the resource-managing object should also copy the resource it wraps. That is, copying a resource-managing object performs a "deep copy."

    Some implementations of the standard string type consist of pointers to heap memory, where the characters making up the string are stored. Objects of suchstrings contain a pointer to the heap memory. When astring object is copied, a copy is made of both the pointer and the memory it points to. Suchstrings exhibit deep copying.

  • Transfer ownership of the underlying resource. On rare occasion, you may wish to make sure that only one RAII object refers to a raw resource and that when the RAII object is copied, ownership of the resource is transferred from the copied object to the copying object. As explained inItem 13, this is the meaning of "copy" used byauto_ptr.

tr1::shared_ptr and auto_ptr both offer a get member function to perform an explicit conversion, i.e., to return (a copy of) the raw pointer inside the smart pointer object:

int days = daysHeld(pInv.get());            // fine, passes the raw pointer

                                            // in pInv to daysHeld


2.

class Font {                           // RAII class

public:

  explicit Font(FontHandle fh)         // acquire resource;

  : f(fh)                              // use pass-by-value, because the

  {}                                   // C API does


operator FontHandle() const { return f; }        // implicit conversion function(The pattern of implicit conversion function)
//convert to type FontHandle()
~Font() { releaseFont(f); } // release resourceprivate: FontHandle f; // the raw font resource};
3.
std::string *stringPtr1 = new std::string;



std::string *stringPtr2 = new std::string[100];

...



delete stringPtr1;                       // delete an object



delete [] stringPtr2;                    // delete an array of objects
The rule is simple: if you use [] in a new expression, you must use [] in the corresponding delete expression. If you don't use [] in a new expression, don't use [] in the matching delete expression.

4. 
  • Store newed objects in smart pointers in standalone statements. Failure to do this can lead to subtle resource leaks when exceptions are thrown

    processWidget(std::tr1::shared_ptr<Widget>(new Widget), priority());

    C++ compilers are granted considerable latitude in determining the order in which these things are to be done. (This is different from the way languages like Java and C# work, where function parameters are always evaluated in a particular order.) The "new Widget" expression must be executed before the tr1::shared_ptr constructor can be called, because the result of the expression is passed as an argument to thetr1::shared_ptr constructor, but the call to priority can be performed first, second, or third. If compilers choose to perform it second (something that may allow them to generate more efficient code), we end up with this sequence of operations:

    1. Execute "new Widget".

    2. Call priority.

    3. Call the tr1::shared_ptr constructor.

    But consider what will happen if the call to priority yields an exception. In that case, the pointer returned from "new Widget" will be lost, because it won't have been stored in theTR1::shared_ptr we were expecting would guard against resource leaks. 

    The way to avoid problems like this is simple: use a separate statement to create theWidget and store it in a smart pointer, then pass the smart pointer to processWidget:

    std::tr1::shared_ptr<Widget> pw(new Widget);  // store newed object
    
                                                  // in a smart pointer in a
    
                                                  // standalone statement
    
    
    
    processWidget(pw, priority());                // this call won't leak
    
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值