#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;
}
输出:
a的地址= 0x7ffeee1c9b38
s的地址= 0x7fbdc0405900
为什么a和s的地址不同?
它们具有不同的地址,因为它们是不同的对象。来自cppreference关于throw
:
throw expression
[...]
- 首先,从表达式复制初始化异常对象
[...]
通过引用进行捕获的原因并不是为了避免复制而是为了正确捕获从其他继承的异常。对于int
没有关系。
出于好奇,这是a
在catch块中获取引用的方法:
#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';
}
}
可能的输出:
Address of a = 0x7ffd76b7c2d4
Address of s = 0x7ffd76b7c2d4
PS:以防万一,您对我的代码做了更多更改,因为为什么“使用命名空间标准”;被认为是不良做法?,“ std :: endl”和“ \ n”,因为在中return 0
是多余的main
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句