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_INCREMENT_REGISTRATION_GROUP() 12 #include <iostream> 13 14 struct file { filefile15 file(void) : open_(false) {} filefile16 file(char const* path) : open_(false) { open(path); } 17 openfile18 void open(char const* path) { open_ = true; } closefile19 void close(void) { open_ = false; } is_openfile20 bool is_open(void) const { return open_; } 21 22 private: 23 bool open_; 24 }; BOOST_TYPEOF_REGISTER_TYPE(file)25BOOST_TYPEOF_REGISTER_TYPE(file) 26 27 void bad(void) { 28 //[try_catch_bad_seq 29 file passwd; 30 try { 31 passwd.open("/etc/passwd"); 32 // ... 33 passwd.close(); 34 } catch(...) { 35 std::clog << "could not get user info" << std::endl; 36 if(passwd.is_open()) passwd.close(); 37 throw; 38 } 39 //] 40 } 41 good(void)42void good(void) { 43 //[try_catch_good_seq 44 try { 45 file passwd("/etc/passwd"); 46 BOOST_SCOPE_EXIT( (&passwd) ) { 47 passwd.close(); 48 } BOOST_SCOPE_EXIT_END 49 } catch(...) { 50 std::clog << "could not get user info" << std::endl; 51 throw; 52 } 53 //] 54 } 55 main(void)56int main(void) { 57 bad(); 58 good(); 59 return 0; 60 } 61 62