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/config.hpp> 10 #ifdef BOOST_NO_CXX11_LAMBDAS 11 # error "lambda functions required" 12 #else 13 14 #include <boost/detail/lightweight_test.hpp> 15 #include <vector> 16 17 struct person {}; 18 19 struct world { 20 void add_person(person const& a_person); 21 std::vector<person> persons_; 22 }; 23 24 //[world_cxx11_lambda 25 #include <functional> 26 27 struct scope_exit { scope_exitscope_exit28 scope_exit(std::function<void (void)> f) : f_(f) {} ~scope_exitscope_exit29 ~scope_exit(void) { f_(); } 30 private: 31 std::function<void (void)> f_; 32 }; 33 add_person(person const & a_person)34void world::add_person(person const& a_person) { 35 bool commit = false; 36 37 persons_.push_back(a_person); 38 scope_exit on_exit1([&commit, this](void) { // Use C++11 lambda. 39 if(!commit) persons_.pop_back(); // `persons_` via captured `this`. 40 }); 41 42 // ... 43 44 commit = true; 45 } 46 //] 47 main(void)48int main(void) { 49 world w; 50 person p; 51 w.add_person(p); 52 BOOST_TEST(w.persons_.size() == 1); 53 return boost::report_errors(); 54 } 55 56 #endif // LAMBDAS 57 58