Reprint: Https://www.jianshu.com/p/b7ffe79498be what is RAII.
RAII is the abbreviation for the resource acquisition is initialization (translated as "resource acquisition is initialized" above the wiki) and is a customary method of managing resources and avoiding leaks in the C + + language. Using the principle that C + + constructs objects will eventually be destroyed. Raii's approach is to use an object, to obtain the corresponding resources during its construction, to control access to the resource during the object's lifetime, to keep it valid, and finally to release the resource acquired at the time of the object's destructor. why to use RAII.
It says RAII is a way to manage resources and avoid resource leaks. So, it took so long, but also wrote so many programs, verbally often say resources, then how resources are defined. In computer systems, resources are a limited number of elements that have a certain effect on the normal operation of the system. For example: Network sockets, mutexes, file handles and memory, and so on, they belong to system resources. Because the system's resources are limited, just like the natural oil, iron ore, is not inexhaustible, so we use system resources in programming, must follow a step:
1 application resources;
2 use of resources;
3 Release resources.
The first and second steps are indispensable, because resources must be applied to use, after the use is completed, must be released, if not released, it will cause resource leaks.
One of the simplest examples:
#include <iostream>
using namespace std;
int main ()
{
int *testarray = new int [];
Here, you can use the array
delete [] testarray;
Testarray = NULL;
return 0;
}
Summary:
But if the program is complex, the need for all the new allocated memory delete, resulting in extremely bloated, inefficient, and, more frightening, the program's understandable and maintainability significantly reduced, when the operation increased, processing resources to release the code will be more and more chaotic. What to do if the statement that freed the resource was not invoked when an exception occurred in an operation. This time, the RAII mechanism can come in handy. how to use Raii.
When we use local variables inside a function, this variable is not destroyed when the scope of the local variable is exited; When the variable is a class object, this time it automatically calls the destructor of the class, and all of this happens automatically, without the programmer showing the call done. This is too good, RAII is the way to complete.
Classes in C + + have the ability to invoke destructors automatically because the resources of the system do not have automatic release capabilities. If the resource is encapsulated with a class, the resource operations are encapsulated within the class, freeing the resource in the destructor. When the life of a defined local variable ends, its destructor is invoked automatically, so that the operation of the freed resource is not invoked without the programmer's display.
Code using the RAII mechanism:
#include <iostream>
using namespace std;
Class Arrayoperation
{public
:
arrayoperation ()
{
m_array = new int [ten];
}
void Initarray ()
{for
(int i = 0; i < ++i)
{
* (M_array + i) = i;
}
}
void Showarray ()
{for
(int i = 0; I <10; ++i)
{
cout<<m_array[i]<<endl;
}
}}
~arrayoperation ()
{
cout<< "~arrayoperation is called" <<endl;
if (M_array!= NULL)
{
delete[] m_array; Thanks to the very sharp review, the details can be attended by the comments in this article 2014.04.13
m_array = NULL;
}
Private:
int *m_array;
};
BOOL Operationa ();
BOOL Operationb ();
int main ()
{
arrayoperation arrayop;
Arrayop.initarray ();
Arrayop.showarray ();
return 0;
}
Code that does not use RAII (without the idea of using classes)
#include <iostream> using namespace std;
BOOL Operationa ();
BOOL Operationb ();
int main () {int *testarray = new int [10]; Here, can use the array if (!
Operationa ()) {//If the operation A failed, we should delete the memory delete [] testarray;
Testarray = NULL;
return 0; } if (!
OPERATIONB ()) {//If the operation A failed, we should delete the memory delete [] testarray;
Testarray = NULL;
return 0;
//All the operation succeed, delete the memory delete [] testarray;
Testarray = NULL;
return 0; BOOL Operationa () {//Do some operation, if the operate succeed, then return true, else return false Retu
RN false; BOOL Operationb () {//Do some operation, if the operate succeed, then return true, else return false Retu
RN true; }
The above example has little practical significance, just to illustrate the mechanism of RAII. Here's a practical example:
#include <iostream> #include <windows.h> #include <process.h> using namespace std;
Critical_section CS;
int gglobal = 0;
Class MyLock {Public:mylock () {entercriticalsection (&CS);
} ~mylock () {leavecriticalsection (&CS);
} private:mylock (const MyLock &);
MyLock operator = (const MyLock &);
}; void Docomplex (MyLock &lock)//Thank you very much for the sharp review 2014.04.13 {} unsigned int __stdcall threadfun (pvoid PV) {my
Lock lock;
int *para = (int *) PV;
I need the lock to do some complex thing Docomplex (lock);
for (int i = 0; i < ++i) {++gglobal;
cout<< "Thread" <<*para<<endl;
cout<<gglobal<<endl;
return 0;
int main () {initializecriticalsection (&CS);
int Thread1, thread2;
Thread1 = 1;
Thread2 = 2;
HANDLE handle[2]; Handle[0] = (handle) _beginthreadex (NULL, 0, Threadfun, ( void *) &thread1, 0, NULL);
HANDLE[1] = (handle) _beginthreadex (null, 0, Threadfun, (void *) &thread2, 0, NULL);
WaitForMultipleObjects (2, handle, TRUE, INFINITE);
return 0; }
This example can be said to be a real project model, when multiple processes access to the critical variables, in order to not appear in the wrong case, the need to lock the critical variable, the above example is the use of Windows critical area implementation of the lock.
However, when using critical_section, EnterCriticalSection and leavecriticalsection must be used in pairs, often forgetting to call LeaveCriticalSection, A deadlock occurs at this time. When I encapsulate access to critical_section into the Mylock class, I just need to define a Mylock variable instead of having to manually show the calling LeaveCriticalSection function.
The above two examples are the RAII mechanism application, understands the above example, should be able to understand the RAII mechanism use.
Author: sexycoder
Link: https://www.jianshu.com/p/b7ffe79498be
Source: Jianshu
Copyright belongs to the author. Commercial reprint please contact the author to obtain authorization, non-commercial reprint please indicate the source.