1

我尝试使用 boost::exception 但遇到了麻烦。我写了以下代码:

struct BaseExceptionXXX : public virtual std::exception, public virtual boost::exception
{
public:
    BaseExceptionXXX()
    { };
    virtual ~BaseExceptionXXX() {};

    BaseExceptionXXX(char const* const message)
        : std::exception(message)
    { }

    BaseExceptionXXX(const std::exception& e)
        : std::exception(e)
    { }

    BaseExceptionXXX(const BaseException& e)
        : std::exception(e)
        , boost::exception(e)
    { }

    bool IsEmpty() const
    {
        const std::string what_err = std::exception::what();
        return (what_err.empty() && boost::get_error_info<UserErrorInfo>(*this) == nullptr);
    }

    const char* what() const throw() override
    {
        return boost::diagnostic_information(*this).c_str(); //<-- crash here
    }
};


int main()
{
    std::string exception_description;

    try
    {
        BOOST_THROW_EXCEPTION(BaseExceptionXXX("hello exception"));
    }
    catch (BaseExceptionXXX& ex)
    {
        exception_description = ex.what(); //<-- crash here
    }
}

但它在函数中崩溃了:boost::diagnostic_information(*this)。它崩溃的原因:堆栈溢出

为什么会发生以及如何以正确的方式使用 boost::exception?

升压版 - 1.66

MSVS2017 版本 - 15.5.5

4

1 回答 1

1

由于无限递归,您正在导致堆栈溢出。在你的实现中what()你写:

const char* what() const throw() override
{
    return boost::diagnostic_information(*this).c_str(); //<-- crash here
}

diagnostic_information但是,很明显,收集的关键部分是what()来自异常的消息。因此,what()将递归调用自身。

于 2018-02-01T22:59:00.147 回答