简体   繁体   中英

Misunderstanding what() function of std::runtime_error

I'm tested Boost.Exception library and faced with inexplicable behavior. 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

#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. So the second example copy-constructs std::exception from the base class of std::runtime_exception , losing the message in the process.

std::exception doesn't have any means to store a custom message; its what() implementation simply returns a hard-coded string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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