简体   繁体   中英

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:

Address of a = 0x7ffeee1c9b38

Address of s = 0x7fbdc0405900

Why are the addresses of a and s different??

They have different adresses, because they are different objects. From cppreference about throw :

 throw expression

[...]

  1. First, copy-initializes the exception object from expression

[...]

The reason to catch by reference is not so much to avoid a copy, but to correctly catch exceptions that inherit from others. For an int it does not matter.


Just as a curiosity, this is how you can get a reference to a in the catch block:

#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';
    }
}

Possible output:

Address of a = 0x7ffd76b7c2d4
Address of s = 0x7ffd76b7c2d4

PS: Just in case you wonder, I changed more on your code, because Why is “using namespace std;” considered bad practice? , "std::endl" vs "\n" , and because return 0 is redundant in main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM