我想同时插入几个STL容器中,要么全部成功,要么全部保持不变。我该如何优雅地做到这一点?
在我的示例中,我有一个带有各种STL容器作为数据成员的自定义容器。插入操作将插入到各种容器中,但是如果其中一个失败,则需要撤消更改以确保所有不变式仍然有效。我该怎么做(很好)?
我的第一个直觉是退回所有插入的内容并撤消它们。尽管我希望我的例子能说明这一点,但这似乎有些过分。
示例(很抱歉,如果不够“最小”):

struct DataItem {
  int x;
  float y;
  char c;
};

class MyContainer {
public:
  void Insert(std::vector<std::string> names,
              std::unordered_set<int> categories,
              DataItem data);
private:
  /* invariant: if a string 'name' is mapped to an id 'i' in 'name_to_id_'
                it must be the position of a 'DataItem' object in 'data_'
                and contained in at least one of the categories */
  std::map<std::string, int> name_to_id_;
  std::map<int, std::unordered_set<int>> categories_;
  std::vector<DataItem> data_;
};

MyContainer::Insert(std::vector<std::string> names,
                    std::unordered_set<Categories> categories,
                    DataItem data) {
  /* ensure names, and categories are not empty and data is valid */
  int id = data_.size();
  for (auto it = names.begin(); it != names.end(); ++it) {
    if (this->name_to_id_.count(name)) {
      /* Clean up all names inserted so far by iterating backwards to names.begin()
         using this->name_to_id_.erase */
      throw SomeException("Insertion failed");
    }
    try {
      this->name_to_id_.insert({*it, id});
    } catch (/* what do I catch here? */) {
      /* Clean up all names inserted so far by iterating backwards to names.begin()
         using this->name_to_id_.erase */
      throw SomeException("Insertion failed");
    }
  }
  for (auto it = categories.begin(); it != categories.end(); ++it) {
    try {
      this->categories_.at(*it).insert(id);
    } catch (/* what do I catch here? */) {
      /* Clean up all names and all categories id was inserted into so far by
         iterating backwards to categories.begin() using
         this->categories_.at(*it).erase(id) */
      throw SomeException("Insertion failed");
    }
  }
  try {
    this->data_.push_back(data);
  } catch (/* what do I catch here? */) {
    /* Once again clean up all categories and names... */
    throw SomeException("Insertion failed");
  }
}
即使没有写出清理内容,这似乎也是多余的。特别是考虑到insertpush_back很少应该以开头失败。这真的是我需要做的吗?
另外,擦除更改的最安全方法是我可以确定std::unordered_setstd::map的组合是finderase,但我找不到关于find的异常安全性的任何信息。它总是成功吗?
我突然想到,必须将insertpush_back语句包装在try块中才能真正处理该异常,但是我能捕获什么异常?

最佳答案

我没有提到实际的清理操作,也没有最有效的方法。您将需要记录在什么阶段插入失败并相应地进行。

struct DataItem {
   int x;
   float y;
   char c;
};

class SomeException : std::exception
{
public:
   SomeException(char *c) : std::exception(c) {};

};

class MyContainer {
public:
   void Insert(std::vector<std::string> names,
      std::unordered_set<int> categories,
      DataItem data);

private:
   void CleanUp();

private:
   /* invariant: if a string 'name' is mapped to an id 'i' in 'name_to_id_'
   it must be the position of a 'DataItem' object in 'data_'
   and contained in at least one of the categories */
   std::map<std::string, int> name_to_id_;
   std::map<int, std::unordered_set<int>> categories_;
   std::vector<DataItem> data_;
};


void MyContainer::CleanUp()
{
   // Do your clean up here
}

void MyContainer::Insert(std::vector<std::string> names,
   std::unordered_set<int> categories,
   DataItem data)
{
   bool failed = false;

   /* ensure names, and categories are not empty and data is valid */
   int id = data_.size();
   for (auto it = names.begin(); it != names.end() && !failed; ++it) {
      if (this->name_to_id_.count(*it))
         failed = true;
      try {
         this->name_to_id_.insert({ *it, id });
      }
      catch (...) {
         failed = true;
      }
   }

   for (auto it = categories.begin(); it != categories.end() && !failed; ++it) {
      try {
         this->categories_.at(*it).insert(id);
      }
      catch (...) {
         failed = true;
      }
   }

   try {
      if (!failed)
         this->data_.push_back(data);
   }
   catch (...) {
      failed = true;
   }

   if (failed)
      CleanUp();
}

关于c++ - 同时插入STL容器并具有强大的异常保证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62970606/

10-11 22:42
查看更多