GCC begins move to C++
GCC begins move to C++
Posted Jun 2, 2010 14:50 UTC (Wed) by endecotp (guest, #36428)In reply to: GCC begins move to C++ by mjthayer
Parent article: GCC begins move to C++
> store several elements into the container. An exception occurs
> half way through. It would be nice to roll back to the state
> you were in before the method was called
If your container is a linked list like std::list, you do it something like this (pseudo-code):
list tmp_list;
for (.....) {
tmp_list.push_back(....);
}
main_list.splice(main_list.end(),tmp_list);
list::splice cannot normally throw, so to addition of the new items to the main list is atomic. If an exception occurs during the loop, the temporary list is destroyed during unwinding and the main list is never touched. splice() just involves a handful of pointer swaps so there is no efficiency issue with this code.
If your container is more like a std::vector it's a bit more verbose; I would write something like this (pseduo-code):
size_t old_size = main_list.size();
try {
for (......) {
main_list.push_back(.....);
}
}
catch (...) {
main_list.resize(old_size);
throw;
}
You could wrap that up into something more transactional-looking if you wanted (pseudo-code):
{
transaction t(main_list);
for (......) {
main_list.push_back(....);
}
t.commit();
}
where transaction's ctor saves the old size and the dtor calls resize() unless commit() has been called.
> not quite trivial either
No it's not quite trivial, but I would hope that anyone who has got their "C++ programmer's license" would be able to do it.
Phil.
