c++ - 无法通过 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;
}
输出:
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;” 被认为是不好的做法?, "std::endl" vs "\n",因为return 0
在main
.
推荐阅读
- javascript - JS转换为ASCII数字并反转
- jquery - 如何使用ajax刷新mvc razor中的列表框
- html - 使用 Angular 2+ 引导
- count - Power BI,如何汇总下表(Max,distinctcount)
- hive - 是否可以仅将 Avro 文件中的选定列加载到 Hive?
- jquery - 页脚和图像之间的空间
- javascript - 如何从 html 代码重新加载 DataTable
- ruby - 将多个类一起用作哈希键
- html - 每次单击输入字段时,如何在纵向视图中停止我的移动网站上的 html 表单从浮动到横向视图?
- angular - npm Install Boostrap font-awesome network error