![](/img/trans.png)
[英]What is wrong with this C++ exception syntax (std::runtime_error)?
[英]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.