world_cxx11_lambda.cpp 1.2 KB

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