Re: why should throwing an exception by reference work
"Tom1s" <NULL@NULL.NULL> wrote in message
news:Jzu8g.9030$j7.305361@news.indigo.ie
"puzzlecracker" <ironsel2000@gmail.com> wrote in message
news:1147302904.840900.226670@i39g2000cwa.googlegroups.com
void bar(){
MyExcepton ex(); //MyException inherits from Excetpion
That's a very pretty function declaration you have there. It's
exactly the same as writing:
MyException ex(void);
ReturnType FunctionName(ParameterList);
What you want is:
My Exception ex;
Exception &exRef=ex;
throw exRef;
}
void foo(){
try{
bar();
}catch( Exception &ex){
You have an invalid reference here, because the object to which it
refers has gone out of scope (i.e. has been destroyed).
I don't believe that is correct. Consider:
#include <iostream>
using namespace std;
struct MyException
{
int a;
};
void bar()
{
MyException me = {4};
MyException &meRef = me;
throw meRef;
}
int main()
{
try
{
bar();
}
catch( MyException &me)
{
cout << "integer is " << me.a << '\n';
}
return 0;
}
This works as it should on VC++ 8 and compiles without warnings on both VC++
8 and Comeau online.
I believe the relevant section of the standard is 15.1/3:
"A throw-expression initializes a temporary object, called the exception
object, the type of which is determined by removing any top-level
cv-qualifiers from the static type of the operand of throw and adjusting the
type from "array of T" or "function returning T" to "pointer to T" or
"pointer to function returning T", respectively. [Note: the temporary object
created for a throw-expression that is a string literal is never of type
char* or wchar_t*; that is, the special conversions for string literals from
the types "array of const char" and "array of const wchar_t" to the types
"pointer to char" and "pointer to wchar_t", respectively (4.2), are never
applied to a throw-expression. ] The temporary is used to initialize the
variable named in the matching handler (15.3)."
On my reading, this means that the throw expression creates its own
temporary, so it is not dependent on the one declared inside bar() in the
code above (15.1/5 says that the creation of the temporary may be eliminated
if it doesn't change the meaning of the program).
It is of some interest to note that it apparently not necessary to make the
argument to catch() const in spite of the fact that it is being initialized
by a temporary.
--
John Carson