这是问题的最小可重现示例:

#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...,但是我得到的只是换行符。

为什么会这样呢?

最佳答案

避免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();
}

07-24 14:12