Let's take a look at the following WebKit code:
{ NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); //Do something else...}
Looking at the implementation of nestinglevelincrementer, we can see that it is equivalent to another method:
{ ++m_scriptNestingLevel; //Do something else... --m_scriptNestingLevel; }
Does the above implementation solve a simple problem by adding a class? In fact, raiI is an important concept in C ++ (* The Key is whether the subsequent execution may throw an exception). More typical is the use of a large number of mutexlocker in WebKit.
What is raiI (response from stackoverflow ):
C ++ does not support 'Finally 'blocks. The reason is that C ++ instead supports raiI :"Resource Acquisition is initialization". The idea is that an object's destructor is responsible for freeing resources. When the object has automatic
Storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception.
(Original address)
You can quickly learn about the attached documents:
RaiI: a powerful tool for C ++ Resource Management
Attached PPT materials:
Two small designs in WebKit
More C ++ idioms:
More C ++ Idioms