Is there a general way to save state variables on a stack in C ++?

In the program I'm working on now, some objects include state variables that are saved with the object. for example, an object representing a point in a 3d model may include a variable to control whether that point has been selected for editing. Quite regularly, one or more of these state variables will be temporarily modified by part of the code, for example.

void MyFunc(); { mytype temp = statevar; statevar = newvalue; DoSomething(); statevar = temp; } 

This has problems, because if DoSomething() throws an exception, statevar is not restored correctly. My planned workaround is to create a new class of templates that restores the value in its dtor. Sort of

 template<class TYPE> class PushState { PushState(TYPE Var) { Temp = Var; } Pop() { Var = Temp; } ~PushState() { Pop(); } TYPE Temp; } void MyFunc(); { PushState<mytype> Push(statevar); DoSomething(); } 

Is there a better way to do this or a well-accepted method of pushing variables onto the stack?

+4
source share
2 answers

Another option is to use the ad hoc RAII class.

For instance:

 void MyFunc(); { class Finally { mytype temp; public: Finally( ) { temp = statevar; } ~Finally() { statevar = temp; } } finally; statevar = newvalue; DoSomething(); } 

Whether the function returns normally or throws an exception, the destructor is called automatically when finally goes out of scope.

+3
source

You can use Boost.ScopeExit . This will create an instance of the object whose destructor will execute the region exit code. It just hides the entire boilerplate code for you.

 #include <boost/scope_exit.hpp> void MyFunc() { mytype temp = statevar; statevar = newvalue; BOOST_SCOPE_EXIT(&statevar) { statevar = temp; } BOOST_SCOPE_EXIT_END DoSomething(); } 
+2
source

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


All Articles