繁体   English   中英

如何调试std :: bad_cast异常

[英]How to debug a std::bad_cast exception

class GAGenome {
  virtual void method(){};
};

template <class T>
class GAArray {
};

template <class T>
class GA1DArrayGenome : public GAArray<T>, public GAGenome {
};

int main() {
  GA1DArrayGenome<float> genome;
  const GAGenome & reference = genome;
  auto cast = dynamic_cast<const GA1DArrayGenome<int> &>(reference);
}

这个明显错误的程序(因为模板参数不同)崩溃了

terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast
Aborted (core dumped)

除了运行时错误消息之外,有没有办法如何精确诊断出错的地方? 有什么东西,可以指出int / float错误给我? 我正在寻找一个描述性的错误消息,如

const GA1DArrayGenome<float> &不能转换为const GA1DArrayGenome<int> &

更好的是,由于C ++类型有时会变得毛茸茸,该工具可能会注意到模板参数中的精确差异。

您也可以放弃直接使用dynamic_cast并将其包装在您自己的模板机器中:

#include <sstream>

class my_bad_cast: public std::bad_cast {
public:
    my_bad_cast(char const* s, char const* d): _source(s), _destination(d) {
#ifdef WITH_BETTER_WHAT
        try {
            std::ostringstream oss;
            oss << "Could not cast '" << _source
                << "' into '" << _destination << "'";
            _what = oss.str();
        } catch (...) {
            _what.clear();
        }
#endif
    }

    char const* source() const { return _source; }
    char const* destination() const { return _destination; }

#ifdef WITH_BETTER_WHAT
    virtual char const* what() const noexcept {
        return not _what.empty() ? _what.c_str() : std::bad_cast::what();
    }
#endif

private:
    char const* _source;
    char const* _destination;
#ifdef WITH_BETTER_WHAT
    std::string _what;
#endif
    // you can even add a stack trace
};

template <typename D, typename S>
D my_dynamic_cast(S&& s) {
    try {
        return dynamic_cast<D>(std::forward<S>(s));
    } catch(std::bad_cast const&) {
        throw my_bad_cast(typeid(S).name(), typeid(D).name());
    }
}

您可以在gbd中加载程序(使用调试信息编译,例如gcc和glang中的-g ),告诉gdb使用catch throw捕获异常,然后查看调用堆栈以查看抛出异常的确切位置。

dynamic_cast在运行时失败时抛出std::bad_cast

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM