[英]Can't catch thrown exception by reference in c++
#include <iostream>
using namespace std;
int main() {
int a = 3;
cout<<"Address of a = "<<&a<<endl;
try{
throw a;
}catch(int& s){
cout<<"Address of s = "<<&s<<endl;
}
return 0;
}
Output:
a的地址=0x7ffeee1c9b38
s 的地址 = 0x7fbdc0405900
為什么a和s的地址不一樣??
它們有不同的地址,因為它們是不同的對象。 從cppreference關於throw
:
throw expression
[...]
- 首先,復制初始化表達式中的異常 object
[...]
通過引用捕獲的原因與其說是為了避免復制,不如說是為了正確地捕獲繼承自他人的異常。 對於int
來說,這無關緊要。
出於好奇,您可以通過以下方式在 catch 塊中獲取對a
的引用:
#include <iostream>
struct my_exception {
int& x;
};
int main() {
int a = 3;
std::cout << "Address of a = " << &a << '\n';
try {
throw my_exception{a};
} catch(my_exception& s) {
std::cout << "Address of s = " << &s.x << '\n';
}
}
可能的 output:
Address of a = 0x7ffd76b7c2d4
Address of s = 0x7ffd76b7c2d4
PS:以防萬一你想知道,我對你的代碼進行了更多更改,因為為什么“使用命名空間標准;” 被認為是不好的做法? , "std::endl" vs "\n" ,因為return 0
在main
中是多余的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.