C++ exception - what is wrong?
by Jerry Mcguire from LinuxQuestions.org on (#51GQM)
The e.what() prints rubbish. Why is that?
Code:#include <iostream>
#include <sstream>
#include <exception>
class myexception : public std::exception
{
public:
virtual const char* what() const throw()
{
return sstr.str().c_str();
}
std::ostringstream sstr;
};
int main() {
try
{
myexception ex;
ex.sstr << "very good";
throw ex;
}
catch (std::exception& e)
{
std::cout << e.what() << '\n'; // <-breakpoint
}
return 0;
}I can still see "very good" at the breakpoint, but the output is just rubbish. Why is that?
Another question is, when is ex destroyed? Does it make sense to catch a reference rather than a copy?


Code:#include <iostream>
#include <sstream>
#include <exception>
class myexception : public std::exception
{
public:
virtual const char* what() const throw()
{
return sstr.str().c_str();
}
std::ostringstream sstr;
};
int main() {
try
{
myexception ex;
ex.sstr << "very good";
throw ex;
}
catch (std::exception& e)
{
std::cout << e.what() << '\n'; // <-breakpoint
}
return 0;
}I can still see "very good" at the breakpoint, but the output is just rubbish. Why is that?
Another question is, when is ex destroyed? Does it make sense to catch a reference rather than a copy?