Exception Safety example guarantee correct?

529 Views Asked by At

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

  • the Strong Exception Safety guarantee
  • Is Exception Neutral, w.r.t to LT
2

There are 2 best solutions below

0
On BEST ANSWER

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

Exception neutral means that you let the exceptions propagate.

2
On

It is exception safe. To be more safe, why not use vector<shared_ptr<int>>

template<typename Type, typename Func>
void StrongSort( vector<shared_ptr<Type>>& elems, Func fun)
{
    vector<shared_ptr<Type>> temp ( elems.begin(), elems.end());
    sort(temp.begin(), temp.end(), fun);
    swap(elems, temp);
}

vector<shared_ptr<int>> ints;
ints.push_back(shared_ptr<int>(new int(3)));
ints.push_back(shared_ptr<int>(new int(1)));
ints.push_back(shared_ptr<int>(new int(2)));
StrongSort(ints, [](shared_ptr<int> x, shared_ptr<int> y) -> bool { return *x < *y; });