Hi,
I would like to know why objects that are thrown to be caught are
copy-constructed more than once.
I have seen this behaviour after running the following simple program
that is an exercise (adapted from F.Brokken C++ Annotations) only to
see constructors at work:
/* exception.cpp */
#include <iostream>
#include <string>
using namespace std;
class Object
{
string name;
public:
Object(string n)
:name(n)
{
cout << "Object constructor of " << name << "\n";
}
Object(Object const &other)
:name(other.name + " (copy)")
{
cout << "Copy constructor for " << name << "\n";
}
~Object()
{
cout << "Object destructor of " << name << "\n";
}
friend void fun_1(Object obj)
{}
void fun_2()
{
Object Thrown("local object");
throw Thrown;
}
char const *get()
{
return name.c_str();
}
};
int main()
{
Object out("main object");
fun_1(out);
try
{
out.fun_2();
}
catch(Object obj)
{
cout << "Caught exception from " << obj.get() << "\n";
}
}
This is the output:
[myself@localhost /temporary]# ./exception
Object constructor of main object
Copy constructor for main object (copy)
Object destructor of main object (copy)
Object constructor of local object
Copy constructor for local object (copy)
Object destructor of local object
Copy constructor for local object (copy) (copy)
Caught exception from local object (copy) (copy)
Object destructor of local object (copy) (copy)
Object destructor of local object (copy)
Object destructor of main object
As you can see the copy constructor adds "(copy)" to the name of the
newly created object. I also put the call to fun_1() just to persuade
myself that an object that is passed by value is copied only once.
May be I am missing something obvious.
Thank you all in advance,
Fabio De Francesco.