0

Suppose I have the following code. The first try-catch behaves as expected. I get a "caught hello". The second try catch, instead, reports caught 0x501da8 (a pointer). In the second case, a temporary stringstream subclass is created. In its destructor (thus before the base aka stringstream is deconstructed) I call str of the underlying stringstream, and use it to create the runtime_error. Why does the code does not work in the second case? (compiling with -fno-elide-constructors makes no difference)

#include <sstream>
#include <iostream>
#include <stdexcept>

class S:public std::stringstream{
public:   
  ~S(){      
    throw std::runtime_error(str());
  }
};


void f(){
  S a;  
  a<<"hello";
}

void g(){
  S()<<"hello";
}

int main(){
  try{
    f();
  }catch(std::runtime_error& b){
    std::cout<<"caught "<<b.what()<<std::endl;
  }

  try{
    g();
  }catch(std::runtime_error& b){
    std::cout<<"caught "<<b.what()<<std::endl;
  }
}

The ideas was the following. Create an "exception stream" where I << all the error details, and let the destructor throw (so I am sure I cannot forget to throw once I created the stream). Something like if (failcondition){ S()<<"some error "<<someinfo; } Is there a way to properly achieve such behavior?

Fabio Dalla Libera
  • 1,297
  • 1
  • 10
  • 24

0 Answers0