Article 51GQM C++ exception - what is wrong?

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?latest?d=yIl2AUoC8zA latest?i=Wemys0bRp8s:Btk_Q-dZ5VE:F7zBnMy latest?i=Wemys0bRp8s:Btk_Q-dZ5VE:V_sGLiP latest?d=qj6IDK7rITs latest?i=Wemys0bRp8s:Btk_Q-dZ5VE:gIN9vFwWemys0bRp8s
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments