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