world_seq.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (C) 2006-2009, 2012 Alexander Nasonov
  2. // Copyright (C) 2012 Lorenzo Caminiti
  3. // Distributed under the Boost Software License, Version 1.0
  4. // (see accompanying file LICENSE_1_0.txt or a copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // Home at http://www.boost.org/libs/scope_exit
  7. #include <boost/scope_exit.hpp>
  8. #include <boost/typeof/typeof.hpp>
  9. #include <boost/typeof/std/vector.hpp>
  10. #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
  11. #include <boost/detail/lightweight_test.hpp>
  12. #include <vector>
  13. struct person {};
  14. BOOST_TYPEOF_REGISTER_TYPE(person)
  15. struct world {
  16. void add_person(person const& a_person);
  17. size_t population(void) const { return persons_.size(); }
  18. private:
  19. std::vector<person> persons_;
  20. };
  21. BOOST_TYPEOF_REGISTER_TYPE(world)
  22. //[world_seq
  23. void world::add_person(person const& a_person) {
  24. bool commit = false;
  25. persons_.push_back(a_person); // (1) direct action
  26. // Following block is executed when the enclosing scope exits.
  27. BOOST_SCOPE_EXIT( (&commit) (&persons_) ) {
  28. if(!commit) persons_.pop_back(); // (2) rollback action
  29. } BOOST_SCOPE_EXIT_END
  30. // ... // (3) other operations
  31. commit = true; // (4) disable rollback actions
  32. }
  33. //]
  34. int main(void) {
  35. world w;
  36. person p;
  37. w.add_person(p);
  38. BOOST_TEST(w.population() == 1);
  39. return boost::report_errors();
  40. }