首页 > 解决方案 > 无法通过 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的地址不一样??

标签: c++try-catchpass-by-reference

解决方案


它们有不同的地址,因为它们是不同的对象。从cppreference关于throw

throw expression  

[...]

  1. 首先,从表达式复制初始化异常对象

[...]

通过引用捕获的原因与其说是为了避免复制,不如说是为了正确捕获从其他人继承的异常。对于一个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 0main.


推荐阅读