C++ 当函数只有迭代器时,处理异常和清除异常的正确方法

C++ 当函数只有迭代器时,处理异常和清除异常的正确方法,c++,exception,iterator,C++,Exception,Iterator,根据标题,我很好奇在抛出异常的情况下如何清理部分工作。在本例中,在添加到out迭代器之后 设想一个类似std::copy_if()的函数[为简单起见编写了回调函数] template <typename InputIterator, typename OutputIterator, typename T> void doSomethingIf(InputIterator begin, InputIterator end, OutputIterator outputIterator)

根据标题,我很好奇在抛出异常的情况下如何清理部分工作。在本例中,在添加到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
   }
}
模板
void doSomethingIf(输入迭代器开始、输入迭代器结束、输出迭代器输出迭代器)
{
//为了简单起见,我将把计算分为两部分,并向后推
//将结果发送到输出迭代器
整数计数=标准::距离(开始、结束);
std::向量tmp{};
int i=0;
而(我<计数){
T T=someCalculation(*(begin+i));
tmp.推回(t);
}
//一切都很好,但我们需要得到输出迭代器的所有信息
试一试{
用于(自动t:tmp){
*输出计数器+++=t;
}
}捕获(const std::exception&e){
//如何“撤销”我们的部分工作
}
}
值得注意的是,我称之为

std::vector<int> output{};
std::vector<int> input{}; 
// Fill up input
doSomethingIf(input.begin(), input.end(), std::back_inserter(output));
std::向量输出{};
std::向量输入{};
//填写输入
doSomethingIf(input.begin()、input.end()、std::back_插入器(output));

复制outputiterator的内容,然后在Catch中还原。这取决于很多因素。你能“倒带”输出迭代器吗?您能否先从中读取以保存原始值(以便在引发异常时能够还原它)?什么抛出异常?如果它与
输出迭代器
相关,则可能处于无法进行任何修改或写入的状态。这正是我所担心的。可能很大程度上取决于正在进行的工作|我想说,
doSomethingIf()
没有足够的信息来执行此回滚。确实需要考虑一些问题。这里没有银弹,听起来总比没有好。