Often had to perform the following task: change the state of something, perform an action, and then change the state to the original. For example, in Win32 GDI you need to change the background color, then make a few drawings, and then change the color back.
This can be done directly:
COLORREF oldColor = SetBkColor( deviceContext, newColor );
drawStuff( deviceContext );
SetBkColor( deviceContext, oldColor );
or through a class of brackets that will perform a direct change to the constructor and a reverse change in the destructor:
CBkColorSwitcher switcher( deviceContext, newColor );
drawStuff( deviceContext );
//once control reaches end of block the switcher is destroyed and the change is reverted
The advantage of the cluster class is obvious - if an exception is thrown between the changes, the change is returned correctly. What are the disadvantages?
source
share