自定义runtime_error,如果在#what中使用#c_str(),则错误输出始终为空

时间:2018-09-01 09:53:16

标签: c++ c++11

以下是我的代码,我确定当std :: string时,字符串(s2)具有值

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);
};

但输出始终为“ what:(empty message)”,如下所示

/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

我希望当抛出StdErr时,它可以输出我的附加消息,怎么办?

更新,我在this answer中找到了替代解决方案,但是我仍然感到困惑,我认为return "msg"std::string s = "msg"; return s.c_str();是相同的,为什么抛出错误消息是diff?

1 个答案:

答案 0 :(得分:0)

您需要确保在方法超出范围后,返回的char*所指向的内存仍然存在。一种方法是将s2作为成员存储在班级中:

class StdErr : public std::runtime_error {
public:

    std::string msg;
    std::string s2;

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

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