problem with exception

hi all
i am trying following code and have some query.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class myexn
{
	
public:
	int* ptr;
	myexn()
	{
		ptr = new int;
		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.

can any one help my to find out whats going on ?

using windows visual studio 2010.

thanks in advance.

closed account (zb0S216C)
The copy constructor should take a constant reference to another instance.

Wazzak
Framework is right, just add a const to your copy constructor. What you defined is not a copy contructor.

1
2
3
4
	myexn(const myexn& i)
	{
		cout<<"copy ctor myexn \n";
	}
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class myexn
{
	
public:
	int* ptr;
	myexn()
	{
		ptr = new int;
		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.
Topic archived. No new replies allowed.