简体   繁体   English

误解了std :: runtime_error的what()函数

[英]Misunderstanding what() function of std::runtime_error

I'm tested Boost.Exception library and faced with inexplicable behavior. 我已经测试了Boost.Exception库,并且遇到了莫名其妙的行为。 Outputs of two next samples differ. 接下来的两个样本的输出不同。

#include <iostream>
#include <boost/exception/all.hpp>

typedef boost::error_info<struct tag_my, std::runtime_error> my_info;
struct my_error : virtual boost::exception, virtual std::exception {};

void foo () { throw std::runtime_error("oops!"); }

int main() {
  try {
    try { foo(); }
    catch (const std::runtime_error &e) {
      throw my_error() << my_info(e);
    }
  }
  catch (const boost::exception& be) {
    if (const std::runtime_error *pe = boost::get_error_info<my_info>(be))
      std::cout << "boost error raised: " << pe->what() << std::endl;
  }
}

//output
//boost error raised: oops!

When I changed std::runtime_error to std::exception I got the following 当我将std::runtime_error更改为std::exception我得到了以下内容

#include <iostream>
#include <boost/exception/all.hpp>

typedef boost::error_info<struct tag_my, std::exception> my_info;
struct my_error : virtual boost::exception, virtual std::exception {};

void foo () { throw std::runtime_error("oops!"); }

int main() {
  try {
    try { foo(); }
    catch (const std::exception &e) {
      throw my_error() << my_info(e);
    }
  }
  catch (const boost::exception& be) {
    if (const std::exception *pe = boost::get_error_info<my_info>(be))
      std::cout << "boost error raised: " << pe->what() << std::endl;
  }
}

//output
//boost error raised: std::exception

Why does the second sample generate it's output? 为什么第二个样本生成它的输出?

Object slicing. 对象切片。 boost::error_info makes a copy of the object. boost::error_info复制对象。 So the second example copy-constructs std::exception from the base class of std::runtime_exception , losing the message in the process. 因此,第二个示例从std::runtime_exception的基类中复制构造std::exception ,从而在进程中丢失了消息。

std::exception doesn't have any means to store a custom message; std::exception没有任何方法可以存储自定义消息; its what() implementation simply returns a hard-coded string. 它的what()实现只是返回一个硬编码的字符串。

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

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