Boost logo

Boost Users :

From: Erik Thiele (erik_at_[hidden])
Date: 2004-06-23 10:27:45


hi

in some cases i do assign values to variables just for the life of my
function:

void foo()
{
  bool oldfoorunning = foorunning;
  foorunning = true;
  dojobs();
  dofoooo();
  foorunning = oldfoorunning;
}

now the problem arises when dojobs throws an exception. in order to be
safe i have to do:

void foo()
{
  bool oldfoorunning = foorunning;
  foorunning = true;
  try {
    dojobs();
    dofoooo();
  } catch (...) {
    foorunning = oldfoorunning;
    throw;
  }
  foorunning = oldfoorunning;
}

this is ugly and it can get more ugly by having more than one such
variable. then you stack try/catch into each other and code gets really
ugly and error prone.

for that reason i created a class as follows:

template<class X>
class protassign : public boost::non_copyable {
public:
  inline protassign (X &var_, const X &newvalue)
    : var(var_)
  {
    oldvalue = var;
    var = newvalue;
  }
  inline ~protassign ()
  {
    try {
      var = oldvalue;
    } CATCHDESTRUCTOR; //<-- my special destructor error catching macro,
                       //forget it. (is there an alternative in boost?)
  }
private:
  X &var;
  X oldvalue;
};

now i can do:

void foo()
{
  protassign<bool> foorunning_assigner(foorunning, true);
  dojobs();
  dofoooo();
}

and that's all. is there one such thing in boost already???

cu
erik

-- 
Erik Thiele

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net