Правильный способ обработки исключения и очистки, когда функция имеет только итератор - PullRequest
0 голосов
/ 17 января 2020

Что касается названия, мне любопытно, как убрать частичную работу в случае исключения. В этом случае после добавления к итератору out.

Представьте себе функцию типа std :: copy_if () [обратный вызов для простоты]

template <typename InputIterator, typename OutputIterator, typename T>
void doSomethingIf(InputIterator begin, InputIterator end, OutputIterator outputIterator)
{
   // For simplicity sake I'll divide the calculation and pushing back
   // results to the output iterator
   int count = std::distance(begin, end);
   std::vector<T> tmp{};
   int i = 0;
   while (i < count) {
       T t = someCalculation(*(begin+i));
       tmp.push_back(t);
   }

   // All fine and dandy, but we need to get everything on the output Iterator
   try {
       for (auto t: tmp) {
           *outputIterator++ = t;
       }
   } catch (const std::exception& e) {
       // How to "undo" our partial work
   }
}

Стоит отметить, что я называю это как

std::vector<int> output{};
std::vector<int> input{}; 
// Fill up input
doSomethingIf(input.begin(), input.end(), std::back_inserter(output));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...