Wednesday, April 02, 2008

C++ : Why are objects thrown as exception always copied

When an exception is thrown , the objects are generally copied. To explain this consider the following :

{
MyObject myObject;
cin >> myObject;
throw myObject;
}

if the object myObject was passed by reference then the same myObject would be thrown out . If the same object is thrown out then as soon as it goes out of scope , its destructor would get called and as a result of which some garbage would finally reach the exceptional handling code .

It is for this reason that copies of myObject are thrown rather than the original one .

No comments: