c++exception-safeexception-safety

Exception Safety example guarantee correct?


I discuss the Exception Safety Guaratees and devised an example that I think provides the Strong Guarantee:

template<typename E, typename LT>
void strongSort(vector<E*> &data, LT lt) // works on pointers
{
  vector<E*> temp { data };  // bad_alloc? but 'data' not changed. 
  sort(temp.begin(), temp.end(), lt); // 'lt' might throw!
  swap(temp, data); // considered safe.
}

Just an easy (C++0x)-example how this is used:

int main() {
  vector<int*> data { new int(3), new int(7), new int(2), new int(5) };
  strongSort( data, [](int *a, int *b){ return *a<*b;} );
  for(auto e : data) cout << *e << " ";
}

Assuming LT does not change the elments, but it may throw. Is it correct to assume thiat the code provides


Solution

  • Yes. Strong exception guarantee means that the operation completes successfully or leaves the data unchanged.

    Exception neutral means that you let the exceptions propagate.