#include <iostream>
using namespace std;
int main (int argc, char* const argv[]) {
int a = 20;
cout<<"address of a is "<<&a<<endl;
try{
throw a;
}
catch (int& z) {
cout<<"address of z is "<<&z<<endl;
}
return 0;
}
The address of a is not same as that of z. It means reference doesn’t work in try catch. If not then why compiler is not generating any error? And what does above code mean?
I guess my comment was not so clear so I write something as answer.
When you throw that exception you throw it by value. It means that it’ll be copied (it doesn’t matter if it’s a primitive type or a copied object). Of course when an object is copied then its memory location changes (it’s a new object). Why this? Because exceptions can unroll the stack to find a proper catch block. If you throw something by reference what you may get is garbage (because when a variable goes out of scope it’ll be destroyed). I said may because in reality the compiler does not allow to throw a reference and you’ll always have a copy.
If your exception object is really big you may consider to allocate the object with new and then throw its pointer. But someone has to deallocate it. Are you ready for the risk? Take a look (as example) at the
CExceptionimplementation on MFC and its Delete() method (they try to make this easy but I’m not really happy of that).Maybe you wonder why if you have to throw by value you catch by reference. First because it’s how
std::exceptionis designed to be used (try to call thewhat()method of an exception catched by value). Second because it lets the compiler to perform some optimizations (moreover, even if you do not use std::exception, you won’t create useless copies of that object).