[英]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.