簡體   English   中英

誤解了std :: runtime_error的what()函數

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

我已經測試了Boost.Exception庫,並且遇到了莫名其妙的行為。 接下來的兩個樣本的輸出不同。

#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!

當我將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

為什么第二個樣本生成它的輸出?

對象切片。 boost::error_info復制對象。 因此,第二個示例從std::runtime_exception的基類中復制構造std::exception ,從而在進程中丟失了消息。

std::exception沒有任何方法可以存儲自定義消息; 它的what()實現只是返回一個硬編碼的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM