samedi 1 septembre 2018

custom runtime_error, if I use #c_str() in #what, the error output are always empty

following is my code, I'm sure when std::string, the string(s2) has value

class StdErr : public std::runtime_error {
public:

    std::string msg;

    StdErr(const std::string &m) : runtime_error(m) {
        this->msg = m;
    }

    const char *what() const throw() {
        std::string s = "appended msg";
        std::string s2 = ((std::string) "prpr" + "\n" + s);
        return s2.c_str();
    }
};

int main(int argc, char **argv) {
    throw StdErr("prpr");
    return (0);
};

but the output always "what:(empty message)", like following

/home/roroco/Dropbox/c/ro-c/cmake-build-debug/ex/test_stderr_what_with_newline
terminate called after throwing an instance of 'StdErr'
  what():  
Signal: SIGABRT (Aborted)

Process finished with exit code 1

I hope when throw StdErr, it can output my appended message, how to do?

Aucun commentaire:

Enregistrer un commentaire