class myexn
{
public:
int* ptr;
myexn()
{
ptr = newint;
cout<<"ctor myexn \n";
}
~myexn()
{
delete ptr;
cout<<"dtor myexn \n";
}
myexn(myexn& i)
{
cout<<"copy ctor myexn \n";
}
};
int main()
{
try
{
throw myexn(); //object created
} // goes out of scope destructor called
catch(myexn& i) // same object refer (destroyed one ? or copy of oreginal ?)
{
*(i.ptr) = 24; // fail , but work when copy constructor provided why ?
}
return 0;
}
above code works when i use copy constructor, why?
it fails if i do not provide copy constructor (why ? well compiler will any way
provide one if i don't)
surprisingly copy constructor did not get called nothing printed.
You're not copying the object, so I wouldn't expect the copy constructor to be called. And gcc behaves as I'd expected.
However, Visual Studio (all versions) catch a copy. You can verify this by printing the address of the object. I would not have expected this behaviour.
i tried all your suggestion well one thing sure that copy of object got send even if i am using reference. i think that is correct as after throw, control leaves block , did not return and all object up to that point got destroyed.
but still many confusing things are there here is new code.
class myexn
{
public:
int* ptr;
myexn()
{
ptr = newint;
cout<<"ctor myexn \n";
}
~myexn()
{
delete ptr;
cout<<"dtor myexn \n";
}
myexn(const myexn& i)
{
cout<<"copy ctor myexn \n";
}
};
int main()
{
try
{
myexn i ; //object created
cout<<&i<<endl;
throw i; // calls copy constructor
//throw myexn(); // no copy constructor called code works
} // goes out of scope destructor called
catch(myexn& i) // ok now its copy only
{
cout<<&i<<endl;
*(i.ptr) = 24; // now fails with throw i , but suceed with throw() why ?
}
//both address are different so its not oreginal object either.
return 0;
}
the only surprising part now is throw myexn() , no copy constructor called and code works.