2
#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??

Robert Page
  • 366
  • 4
  • 10

1 Answers1

3

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • How is return 0 redundant? – Robert Page Dec 23 '20 at 14:03
  • @RitobrotoGanguly `main` returns `0` by default, you need not write it – 463035818_is_not_an_ai Dec 23 '20 at 14:04
  • o. I always thought that was an compiler specific implementation. – Robert Page Dec 23 '20 at 14:06
  • 1
    @RitobrotoGanguly https://en.cppreference.com/w/cpp/language/main_function -> special properties 4) – 463035818_is_not_an_ai Dec 23 '20 at 14:08
  • 1
    With my compilers, `"\n"` is slightly better than `'\n'`, because the latter is packed into a `char[2]` of `{c, '\0'}` (where `c` is `'\n'` in this case) and then calls the `char const*` routine. But that's just the compilers I use and is an implementation detail; and other compilers may do it different. Probably optimizes well at `-O1` or better, anyway. – Eljay Dec 23 '20 at 15:18
  • 1
    @Eljay thats interesting. I usually use `"\n"` simply because it is more convenient to type, this time I wanted to do it "right". Actually I don't care too much about performance for stdout, because it is slow anyhow – 463035818_is_not_an_ai Dec 23 '20 at 15:44