之所以使用&
例外與其說多態性作爲避免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!
。
我不明白你的最後一段。按引用傳遞與異常無關,並且在C++中基本允許運行時多態。 –
答案是否定的 - 您可以捕獲的對象必須來自您捕獲的異常類型,正如您在文章中提到的那樣。這表現出IS-A關係。如果您只在catch子句中指定子項,則無法捕獲父類。 – Chris