| 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_VARIADIC_MACROS |
| 11 | # error "variadic macros required" |
| 12 | #else |
| 13 | |
| 14 | #include <boost/scope_exit.hpp> |
| 15 | #include <boost/typeof/typeof.hpp> |
| 16 | #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() |
| 17 | #include <iostream> |
| 18 | |
| 19 | struct file { |
| 20 | file(void) : open_(false) {} |
| 21 | file(char const* path) : open_(false) { open(path); } |
| 22 | |
| 23 | void open(char const* path) { open_ = true; } |
| 24 | void close(void) { open_ = false; } |
| 25 | bool is_open(void) const { return open_; } |
| 26 | |
| 27 | private: |
| 28 | bool open_; |
| 29 | }; |
| 30 | BOOST_TYPEOF_REGISTER_TYPE(file) |
| 31 | |
| 32 | void bad(void) { |
| 33 | //[try_catch_bad |
| 34 | file passwd; |
| 35 | try { |
| 36 | passwd.open(path: "/etc/passwd"); |
| 37 | // ... |
| 38 | passwd.close(); |
| 39 | } catch(...) { |
| 40 | std::clog << "could not get user info"<< std::endl; |
| 41 | if(passwd.is_open()) passwd.close(); |
| 42 | throw; |
| 43 | } |
| 44 | //] |
| 45 | } |
| 46 | |
| 47 | void good(void) { |
| 48 | //[try_catch_good |
| 49 | try { |
| 50 | file passwd("/etc/passwd"); |
| 51 | BOOST_SCOPE_EXIT(&passwd) { |
| 52 | passwd.close(); |
| 53 | } BOOST_SCOPE_EXIT_END |
| 54 | } catch(...) { |
| 55 | std::clog << "could not get user info"<< std::endl; |
| 56 | throw; |
| 57 | } |
| 58 | //] |
| 59 | } |
| 60 | |
| 61 | int main(void) { |
| 62 | bad(); |
| 63 | good(); |
| 64 | return 0; |
| 65 | } |
| 66 | |
| 67 | #endif // variadic macros |
| 68 | |
| 69 |
