无法通过 C++ 中的引用捕获抛出的异常
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;
}
输出:
a的地址=0x7ffeee1c9b38
s 的地址 = 0x7fbdc0405900
为什么a和s的地址不一样??
它们有不同的地址,因为它们是不同的对象。来自 cppreference 关于 throw
:
throw expression
[...]
- First, copy-initializes the exception object from expression
[...]
通过引用捕获的原因与其说是为了避免复制,不如说是为了正确地捕获继承自他人的异常。对于 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';
}
}
可能的输出:
Address of a = 0x7ffd76b7c2d4
Address of s = 0x7ffd76b7c2d4
PS:以防万一你想知道,我对你的代码做了更多更改,因为 Why is “using namespace std;” considered bad practice?, "std::endl" vs "\n", and because return 0
is redundant in main
.
#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
[...]
- First, copy-initializes the exception object from expression
[...]
通过引用捕获的原因与其说是为了避免复制,不如说是为了正确地捕获继承自他人的异常。对于 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';
}
}
可能的输出:
Address of a = 0x7ffd76b7c2d4
Address of s = 0x7ffd76b7c2d4
PS:以防万一你想知道,我对你的代码做了更多更改,因为 Why is “using namespace std;” considered bad practice?, "std::endl" vs "\n", and because return 0
is redundant in main
.