• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 {
filefile20     file(void) : open_(false) {}
filefile21     file(char const* path) : open_(false) { open(path); }
22 
openfile23     void open(char const* path) { open_ = true; }
closefile24     void close(void) { open_ = false; }
is_openfile25     bool is_open(void) const { return open_; }
26 
27 private:
28     bool open_;
29 };
BOOST_TYPEOF_REGISTER_TYPE(file)30 BOOST_TYPEOF_REGISTER_TYPE(file)
31 
32 void bad(void) {
33     //[try_catch_bad
34     file passwd;
35     try {
36         passwd.open("/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 
good(void)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 
main(void)61 int main(void) {
62     bad();
63     good();
64     return 0;
65 }
66 
67 #endif // variadic macros
68 
69