fork(4) download
  1. // RAII
  2. #include <iostream>
  3. #include <stdio.h>
  4. #include <stdexcept>
  5.  
  6. using namespace std;
  7.  
  8. void f();
  9.  
  10. // use an object to represent a resource
  11. class File_handle { // belongs in some support library
  12. FILE* p;
  13. public:
  14. File_handle(const char* pp, const char* r) {
  15. p = fopen(pp,r);
  16. // Commented out for running on Ideone.com
  17. // if (p==0) throw std::runtime_error("File_error{pp,r}");
  18. }
  19.  
  20. File_handle(const string& s, const char* r) {
  21. p = fopen(s.c_str(),r);
  22. // Commented out for running on Ideone.com
  23. //if (p==0) throw std::runtime_error("File_error{s,r}");
  24. }
  25.  
  26. ~File_handle() {
  27. cout << "fclose() called in File_handle" << endl;
  28. fclose(p);
  29. } // destructor
  30. // copy operations
  31. // access functions
  32. };
  33.  
  34. struct A
  35. {
  36. ~A() {
  37. cout << "~A() called" << endl;
  38. };
  39. };
  40.  
  41. void good (string s) {
  42. File_handle fh (s, "r");
  43. // use fh
  44. f(); // OOPS!
  45. }
  46.  
  47. void bad(const char* p)
  48. {
  49. FILE* fh = fopen(p,"r"); // acquire
  50. // use f
  51. f(); // OOPS!
  52. fclose(fh); // release
  53. cout << "fclose() called" << endl;
  54. }
  55.  
  56. void f()
  57. {
  58. A a;
  59. throw 42;
  60. }
  61.  
  62. int main() {
  63.  
  64. try
  65. {
  66. // Try either of these
  67. //f();
  68. //bad("c:\\temp\\1.txt");
  69. //good("c:\\temp\\1.txt");
  70. }
  71. catch ( ... ) {}
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0s 2892KB
stdin
Standard input is empty
stdout
Standard output is empty