What could be the reason not to use parenthesis classes in C ++?

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?

+3
source share
6 answers

I'm nitpicking here, but:

  • , - .
  • .
  • .
  • , (, , )
+1

++, RAII. API Win32 - API- C, . ++, RAII, API C ++. Java- RAII finally.

+12

, , . . , . .

CBkColorSwitcher * switcher = new CBkColorSwitcher(......)

, ,

+4

. (, , ?)

+2

, , , ( , ):

  • , , -.
  • , .

, RAII - "" , .

+2

, , , , .

() RAII , , .

. , shared_ptr . , , , .

+1

Source: https://habr.com/ru/post/1714967/


All Articles