Search code examples
c++raii

What could be a reason to not use bracket classes in C++?


It's often needed to accomplish the following task: change the state of something, do action, then change the state back to original. For example, in Win32 GDI it's needed to change background color, then do some drawing, then change the color back.

It can be either done directly:

COLORREF oldColor = SetBkColor( deviceContext, newColor );
drawStuff( deviceContext );
SetBkColor( deviceContext, oldColor );

or via a bracket class that would do the forward change in the constructor and the backward 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 a bracket class is obvious - if an exception is thrown in between the changes the change is reverted correctly. What are the disadvantages?


Solution

  • I'm nitpicking here, but:

    1. Code size, your code will be bigger because of the exception handler.
    2. You need to write a lot of class to handle all sort of switches.
    3. Bigger stack.
    4. Always preforming code on all exceptions, even if its not need (for example you just want the application to crash)