Strong guarantee method calling reliable guarantee methods

When I have a method that calls a set of methods that provide a reliable guarantee, I often have the problem of rolling back changes to also have a strong guarantee method. Let an example be used:

// Would like this to offer strong guarantee
void MacroMethod() throw(...)
{
  int i = 0;
  try
  {
    for(i = 0; i < 100; ++i)
       SetMethod(i); // this might throw
  }
  catch(const std::exception& _e)
  {
    // Undo changes that were done
    for(int j = i; j >= 0; --j)
      UnsetMethod(j); // this might throw
    throw;
  }
}

// Offers strong guarantee
void SetMethod(int i) throw(...)
{
  // Does a change on member i
}

// Offers strong guarantee
void UnsetMethod() throw(...)
{
  // Undoes a change on member i
}

Obviously, UnsetMethod could give up. In this case, my MacroMathod () offers only a basic guarantee. However, I did everything I could to offer a reliable guarantee, but I cannot be absolutely sure that my UnsetMethod () will not throw. Here are my questions:

  • Should I even try to offer a strong guarantee in this case?
  • Should I document my MacroMethod () as having a basic or strong guarantee? Even if it is very unlikely that UnsetMethod will throw?
  • ?
  • , , UnsetMethod() , , catch?

!

+3
4

, . , ( ). , .

, try...catch - , . , , .

+6

MacroMethod() , UnsetMethod(), , . , , , .

UnsetMethod() SetMethod(). UnsetMethod() , ? , .

+1
  • , , . , , , , SetMethod . , .
  • : , UnsetMethod , . , , . .
  • , . 1.
  • , .
+1

, , , , - , , , , swap ( ) "" .

psudocode:

void MacroMethod() throw(...)
{
  int i = 0;
  MyValues working_copy[100] = *this;  //obviously this is psudocode as I don't know your real code
  for(i = 0; i < 100; ++i)
     working_vopy[i].SetMethod(i); // if this throws the exception will propogate out, and no changes will be made
  swap( *this, working_copy);  // this must not throw
}
0

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


All Articles