world.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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/config.hpp>
  8. #ifdef BOOST_NO_CXX11_VARIADIC_MACROS
  9. # error "variadic macros required"
  10. #else
  11. #include <boost/scope_exit.hpp>
  12. #include <boost/typeof/typeof.hpp>
  13. #include <boost/typeof/std/vector.hpp>
  14. #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
  15. #include <boost/detail/lightweight_test.hpp>
  16. #include <vector>
  17. struct person {};
  18. BOOST_TYPEOF_REGISTER_TYPE(person)
  19. struct world {
  20. void add_person(person const& a_person);
  21. size_t population(void) const { return persons_.size(); }
  22. private:
  23. std::vector<person> persons_;
  24. };
  25. BOOST_TYPEOF_REGISTER_TYPE(world)
  26. //[world
  27. void world::add_person(person const& a_person) {
  28. bool commit = false;
  29. persons_.push_back(a_person); // (1) direct action
  30. // Following block is executed when the enclosing scope exits.
  31. BOOST_SCOPE_EXIT(&commit, &persons_) {
  32. if(!commit) persons_.pop_back(); // (2) rollback action
  33. } BOOST_SCOPE_EXIT_END
  34. // ... // (3) other operations
  35. commit = true; // (4) disable rollback actions
  36. }
  37. //]
  38. int main(void) {
  39. world w;
  40. person p;
  41. w.add_person(p);
  42. BOOST_TEST(w.population() == 1);
  43. return boost::report_errors();
  44. }
  45. #endif // variadic macros