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?
source share