C++ 如何用适当的what()函数补充boost::exception

C++ 如何用适当的what()函数补充boost::exception,c++,exception,boost,C++,Exception,Boost,我很喜欢,但我很担心它没有提供一个现成的()函数。现在不要搞混了,它确实有一个nice,它包含了我想在假设的what()函数中看到的所有信息,但是因为boost::exception并不是从std::exception继承的what()是std::exception基中的默认无用what(),它对异常没有任何解释 struct my_exception: virtual std::exception, virtual boost::exception { }; 很明显,我试图覆盖what()并

我很喜欢,但我很担心它没有提供一个现成的()函数。现在不要搞混了,它确实有一个nice,它包含了我想在假设的
what()
函数中看到的所有信息,但是因为
boost::exception
并不是从
std::exception
继承的
what()是
std::exception
基中的默认无用
what()
,它对异常没有任何解释

struct my_exception: virtual std::exception, virtual boost::exception { };
很明显,我试图覆盖
what()
并使其返回
boost::diagnostic_information
,但不知怎么的,它就是不起作用,所以我有点困惑。这可能是因为它会循环,但我不太确定

PS:我想实现
what()
正确的原因是,如果您的程序因许多工具而死亡,那么默认情况下,许多工具都会显示它(例如,gnu编译器将显示一个很好的致命错误,并显示what()、boost unit tests工具等)

#包括
struct my_exception:virtualstd::exception,virtualboost::exception{};
结构my_异常2:虚拟std::异常,虚拟boost::异常{
虚拟常量char*what()常量throw(){
返回“什么”;
}
};
结构my_异常3:虚拟std::异常,虚拟boost::异常{
虚拟常量char*what()常量throw(){
返回boost::诊断信息(this).c_str();
}
};
int main(){
试一试{
BOOST_THROW_异常(my_EXCEPTION());
}捕获(const std::exception&e){

std::cout首先,
boost::diagnostic_information
通过(const)引用获取异常,并且
这是一个指针:

    return boost::diagnostic_information(*this).c_str();
                                         ^-- here
其次,一旦您修复了该问题,正如您正确预期的那样,这将导致无限递归,如
boost::diagnostic_information
调用
std::exception::what()
。可以使用一个守卫成员或类似的东西来解决此问题:

struct my_exception3: std::exception, boost::exception {
    mutable bool in_what = false;
    virtual const char* what() const throw() {
        struct g { bool &b; ~g() { b = false; } } guard{in_what};
        return in_what ? "WHAT" : (in_what = true, boost::diagnostic_information(*this).c_str());
    }
};
最后,您使用的是一个已销毁的临时
字符串中的
c_str
。我将把该问题的解决方案留作练习。

,获胜者是

namespace boost {
    char const * diagnostic_information_what( boost::exception const & e ) throw();
}

。我有点恼火,因为它冻结了what()的内容。该死,我找到了下面的真实答案。对于这个不那么聪明的问题,我感到抱歉。如果这个答案解决了这个问题,你最好接受它:3。
namespace boost {
    char const * diagnostic_information_what( boost::exception const & e ) throw();
}