C ++ resource management application skills

Source: Internet
Author: User

C ++ is a powerful programming language that helps developers easily implement various functions. Resource management is a basic knowledge and deserves our attention. Here we will give you a detailed description of C ++ resource management.

  • Detailed introduction to the C ++ file Stream Application Method
  • Explanation of C ++ declarative syntax
  • Basic concepts of C ++ kdevelop
  • Overview of C ++ virtual destructor
  • Skills related to C ++ eof () Functions

My favorite definition of resources is: "Anything that is obtained in your program and released after this. "Memory is an example of a pretty obvious resource. It needs to be obtained using new and released using delete. There are also many other types of resource file handles, important fragments, and GDI resources in Windows. It is also very convenient to promote the concept of resources to all objects created and released in a program, whether the objects are allocated in the heap, in the stack, or globally applied to the internal life.

The possession of a given resource is an object or code that is responsible for releasing the resource. Two levels of ownership are separated: automatic and explicit. If an object is released, it is guaranteed by the language mechanism, this object is automatically owned. For example, if an object is embedded in another object, other objects are required to be cleared. The external object is treated as the owner of the embedded class. Similarly, the release failure of every object created on the stack as an automatic variable) is guaranteed when the control flow leaves the scope defined by the object. In this case, the action is taken as the owner of the object. Note that all automatic ownership is compatible with other language mechanisms, including exceptions. No matter how you exit the scope-normal process control exit, a break statement, a return, a goto, or a throw-Automatic resources can be cleared.

So far, everything is fine! The problem occurs when pointers, handles, and abstractions are introduced. If you access an object through a pointer, for example, if the object is allocated in the heap, C ++ does not automatically pay attention to its release. Programmers must explicitly release these resources using appropriate program methods. For example, if an object is created by calling new, it needs to be recycled using delete. A file is opened using CreateFile (Win32 API) and must be closed using CloseHandle. The Critical Section that uses EnterCritialSection. LeaveCriticalSection is required to exit. There is no owner for a "Bare" pointer, file handle, or critical section status to ensure they are finally released. The basic prerequisite for resource management is to ensure that each C ++ resource management has its own owner.

A pointer, a handle, and a critical section state will own the owner only when we encapsulate them into an object. This is our first rule: allocate resources in the constructor and release resources in the destructor.

When You encapsulate all resources according to the rules, you can ensure that there is no resource leakage in your program. This is obvious when the encapsulated Object Encapsulating Object is created in the stack or embedded in other objects. But what about those dynamic application objects? Don't worry! Any dynamic application is regarded as a resource and encapsulated according to the method mentioned above. The chain of the encapsulated object of this object has to be terminated somewhere. It ends at the highest level of owner, automatic or static. These are the guarantees for releasing resources when the scope is left or the program is released.

The following is a typical example of C ++ resource management. In a multi-threaded application, the problem of sharing objects between threads is solved by connecting such an object to the critical section. Each customer who needs to access Shared resources needs to obtain the critical section. For example, this may be the implementation method of the critical section in Win32.

 
 
  1. class CritSect  
  2. {  
  3. friend class Lock;  
  4. public:  
  5. CritSect () { InitializeCriticalSection (&_critSection); }  
  6. ~CritSect () { DeleteCriticalSection (&_critSection); }  
  7. private  
  8. void Acquire ()  
  9. {  
  10. EnterCriticalSection (&_critSection);  
  11. }  
  12. void Release ()  
  13. {  
  14. LeaveCriticalSection (&_critSection);  
  15. }  
  16. CRITICAL_SECTION _critSection;  
  17. }; 

The smart part here is to ensure that every customer entering the critical section can leave. The status of "entering" critical section is a resource and should be encapsulated. The package is usually called a lock ).

 
 
  1. class Lock  
  2. {  
  3. public:  
  4. Lock (CritSect& critSect) : _critSect (critSect)  
  5. {  
  6. _critSect.Acquire ();  
  7. }  
  8. ~Lock ()  
  9. {  
  10. _critSect.Release ();  
  11. }  
  12. private  
  13. CritSect & _critSect;  
  14. }; 

The general usage of the lock is as follows:

 
 
  1. void Shared::Act () throw (char *)  
  2. {  
  3. Lock lock (_critSect);  
  4. // perform action -- may throw  
  5. // automatic destructor of lock  

Note that no matter what happens, the critical section will be released by means of the language mechanism.

Another thing to remember is that every C ++ resource management needs to be encapsulated separately. This is because resource allocation is a very error-prone operation, and resources are limited. We assume that a failed resource allocation will lead to an exception-in fact, this will happen frequently. So if you want to hit two birds with one stone, or apply for two types of resources in one constructor, you may be in trouble. Just think about what will happen when one type of resource is successfully allocated but the other type of failure throws an exception. Because the constructor has not been fully completed, the Destructor cannot be called, and the first resource will be leaked.

This situation can be easily avoided. Whenever you have a class that requires more than two types of resources, write two smile wrappers to embed them into your class. Each embedded structure can be deleted, even if the packaging class is not constructed.

Related Article

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.