我有一个愚蠢的问题。我读过这篇关于 std::exception 的文章http://www.cplusplus.com/doc/tutorial/exceptions/ http://www.cplusplus.com/doc/tutorial/exceptions/
On catch (exception& e)
, 它说:
我们放置了一个通过引用捕获异常对象的处理程序(请注意类型后面的&符号),因此这也捕获了从异常派生的类,例如类 myexception 的 myex 对象。
这是否意味着通过使用“&”你也可以捕获父类的异常?我认为 & 是在 std::exception 中预定义的,因为将 e (std::exception) 作为引用传递比对象更好。
使用理由&
with except 与其说是多态,不如说是避免slicing http://en.wikipedia.org/wiki/Object_slicing。如果你不使用&
,C++会尝试将抛出的异常复制到新创建的异常中std::exception
,在此过程中可能会丢失信息。例子:
#include <stdexcept>
#include <iostream>
class my_exception : public std::exception {
virtual const char *what() const throw() {
return "Hello, world!";
}
};
int main() {
try {
throw my_exception();
} catch (std::exception e) {
std::cout << e.what() << std::endl;
}
return 0;
}
这将打印默认消息std::exception
(就我而言,St9exception
) 而不是Hello, world!
,因为切片丢失了原来的异常对象。如果我们将其更改为&
:
#include <stdexcept>
#include <iostream>
class my_exception : public std::exception {
virtual const char *what() const throw() {
return "Hello, world!";
}
};
int main() {
try {
throw my_exception();
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
return 0;
}
现在我们确实看到了Hello, world!
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)