RAII Technical Analysis of C + +

Source: Internet
Author: User

1. What is RAII technology?
We often use new in C + + to apply for memory space, but also often forget to delete the space to reclaim the request, prone to memory overflow, so Raii technology was born, to solve such a problem. The RAII (Resource acquisition is initialization) mechanism is first proposed by Bjarne Stroustrup, which is a simple technique that uses the object lifecycle to program resources such as memory, file handles, network connections, mutexes, and so on. We know that some of the members inside the function are placed on the stack space, and when the function returns, the local variables on those stacks will immediately free up space, so Bjarne Stroustrup think that the place where the resource release code is to be run is the destructor of the object placed in the program segment (stack), Because stack winding will guarantee that their destructors will be executed. Raii takes advantage of this characteristic of the variables inside the stack. The general practice of RAII is to get the resource when the object is constructed, and then to control access to the resource so that it remains valid for the lifetime of the object, and finally releases the resource when the object is refactored. In this, we actually managed to manage a resource's responsibility to a local object that is stored in the stack space.
There are two major benefits to this approach:
(1) You do not need to explicitly release resources.
(2) In this way, the resources required by the object remain valid for the duration of their life.

2. Actual Application

2.1 A simple example: pointer application space, freeing space

void Func () {  int *ip = new INT[10];  ...//operations//operations ...  //operations  delete[] ip;//if not free mem, memory overflow}
After using RAII technology:

Template<class pointertype>class my_pointer{public:   my_pointer (pointertype* _ptr, size_t sz)   {_ptr = New pointertype[sz];m_ptr = _ptr;   }   ~my_pointer ()   {delete []m_ptr;   } Protected:   pointertype    m_ptr;}
2.2 Scope Lock (local lock technology)
In many cases, in order to achieve data synchronization between multithreading, we will use technology such as Mutex,critical Section,event,singal. But in the process of use, for various reasons, sometimes we encounter a problem: Due to forget to release (Unlock) lock, resulting in a deadlock phenomenon.
The use of RAII can be a good solution to this problem, using the need not worry about releasing the lock problem. The sample code is as follows:
My_scope_lock is a template class that implements a local lock.
LockType abstract represents a specific lock class. Implements the Mutex_lock class based on a mutex.

Template<class locktype>class my_scope_lock{public   :   my_scope_lock (locktype& _lock): M_lock (_ Lock)   {          m_lock.occupy ();   }   ~my_scope_lock ()   {        m_lock.relase ();   }   Protected:   LockType    M_lock;}
When used:

Mutex_lock  M_mutex_lock; My_scope_lock L_lock (M_mutex_lock);
We can introduce a lot of such examples according to the above example class. It's easy to forget to close files when reading and writing files, and if you borrow RAII technology, you can circumvent this error. such as access to the database, forget to disconnect the database connection and so on can be solved with the help of RAII technology.







Reference article:

A RAII factory implements Http://www.codeproject.com/Articles/10141/RAII-Dynamic-Objects-and-Factories-in-C
RAII Local Lock Technology http://www.cnblogs.com/zhangyunkui/archive/2009/11/13/1602514.html
RAII file Operation http://www.cnblogs.com/gnuhpc/archive/2012/12/04/2802307.html
http://blog.csdn.net/hunter8777/article/details/6327704

RAII Technical Analysis of C + +

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.