fork(2) download
  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4.  
  5. void badFunc(std::stringstream& s)
  6. {
  7. int len = s.str().length();
  8. cout << "badFunc(in operator << ) : length = " << len << " " << s.str().c_str() << endl;
  9. if ( 20 <= len)
  10. {
  11. cout << " => exception!(over 20)" << endl;
  12. throw "operator <<";
  13. }
  14. }
  15.  
  16. void doSomething(std::stringstream& s)
  17. {
  18. int len = s.str().length();
  19. cout << "doSomething(in destructor) : length = " << len << " " << s.str().c_str() << endl;
  20. if ( 15 <= len )
  21. {
  22. cout << " => exception!(over 15)" << endl;
  23. throw "destructor";
  24. }
  25. }
  26.  
  27. class Temporary_t {
  28. std::stringstream& sstr; //not own resource
  29. bool safe;
  30. Temporary_t(std::stringstream& s) : sstr(s), safe(false) { sstr.str(""); }
  31. Temporary_t(const Temporary_t&);
  32. Temporary_t& operator =(const Temporary_t&);
  33. public:
  34. ~Temporary_t() throw(int) { if ( safe ) doSomething(sstr); }
  35. template<typename T> Temporary_t& operator << (const T& data)
  36. { safe = false; sstr << data; badFunc(sstr); safe = true; return *this; }
  37. friend Temporary_t temporary_t(std::stringstream& s);
  38. };
  39. Temporary_t temporary_t(std::stringstream& s) { return Temporary_t(s); }
  40.  
  41.  
  42. int main()
  43. {
  44. std::stringstream s;
  45. try {
  46. temporary_t(s) << "ABCD " << 1234;
  47. throw "other";
  48. }
  49. catch (const char* e) { cout << "catch " << e << endl << endl; }
  50. try {
  51. temporary_t(s) << "ABCDEFGHIJ " << 1234567890;
  52. throw "other";
  53. }
  54. catch (const char* e) { cout << "catch " << e << endl << endl; }
  55. try {
  56. temporary_t(s) << "ABCDEFGHI " << 123456789;
  57. throw "other";
  58. }
  59. catch (const char* e) { cout << "catch " << e << endl; }
  60. catch (...) { cout << "catch else"; }
  61. return 0;
  62. }
  63.  
  64.  
Runtime error #stdin #stdout #stderr 0s 3480KB
stdin
Standard input is empty
stdout
badFunc(in operator << )  : length = 5    ABCD 
badFunc(in operator << )  : length = 9    ABCD 1234
doSomething(in destructor)  :  length = 9    ABCD 1234
catch other

badFunc(in operator << )  : length = 11    ABCDEFGHIJ 
badFunc(in operator << )  : length = 21    ABCDEFGHIJ 1234567890
   => exception!(over 20)
catch operator <<

badFunc(in operator << )  : length = 10    ABCDEFGHI 
badFunc(in operator << )  : length = 19    ABCDEFGHI 123456789
doSomething(in destructor)  :  length = 19    ABCDEFGHI 123456789
   => exception!(over 15)
stderr
terminate called after throwing an instance of 'char const*'