为什么不打印错误信息?

时间:2019-11-10 17:37:09

标签: c++

以下是该问题的最小可重现示例:

#include <iostream>
#include <string>

struct MyEx : public std::exception
{
    std::string name;
    MyEx(std::string name);
    ~MyEx() throw();
    virtual const char* what() const throw();
};

MyEx::MyEx(std::string name):
    name{name}
{}

MyEx::~MyEx() throw() {}

const char* MyEx::what() const throw() {
    std::string msg = name + "...";
    return msg.c_str();
}

int foo() {
    throw MyEx("This is an exception");
}

int main() {
    try {
        int res = foo();
        std::cout << res << std::endl;
    } catch (MyEx& caught) {
        std::cout << caught.what() << std::endl;
    }
}

当我执行用g ++编译的可执行文件时,我应该得到:This is an exception...,但是我得到的只是换行符。

为什么会这样?

1 个答案:

答案 0 :(得分:1)

一种避免 UnholySheep 在评论中提到的“悬空指针”的方法是使msg成为成员变量(但您需要删除const来自what)...

struct MyEx : public std::exception
{
    std::string name;
    std::string msg; // This will stay 'in scope` while object exists
    MyEx(std::string name);
    ~MyEx() throw();
    virtual const char* what() throw(); // Note removal of const
};
//...

const char* MyEx::what() throw() {
    msg = name + "...";
    return msg.c_str();
}