some questions about exceptions

* is that ever possible to throw and catch without a single copying of what's thrown? Example?
* why not throw from a copy constructor? And from operator=?
closed account (1yR4jE8b)
1. You would have to throw a pointer to a heap object (the pointer itself gets copied but the heap object does not):

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
/**
 *	Throwing without copying what's thrown
 */

#include <iostream> 

class Copyable
{
public:
	Copyable(){}
	Copyable(const Copyable& other)
	{
		std::cout << "copied!";
	}
}; 

int main()
{
	try
	{
		throw (new Copyable());
	}
	catch (Copyable* notCopied)
	{
		std::cout << "Object Caught By Pointer";
		delete notCopied;
	}
	return 0;
}


You should not really do this though, because it can make it unclear who is responsible for deleting the heap object when you are done with it in non-trivial code.

2. As for your second question, another user wrote an excellent article about it so I'll just link you to that instead:

http://www.cplusplus.com/articles/jsmith1/

Scroll down to a little passed the half way mark to the section called "What is meant by Exception Safe code"?
Last edited on
Thanks! Well I know about pointer, but it gets copied too. I just was interested, because I read in that frequently referenced C++ FAQ collection something like that object might not be copied. Will it always be copied when thrown as object, not pointer?
What about this?

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
	try
	{
		throw Copyable();
	}
	catch ( const Copyable& notCopied )
	{
		std::cout << "Object Caught By Reference";
	}
	return 0;
}
closed account (1yR4jE8b)
I've always thought the anonymous Copyable would get destroyed when you leave the scope
of the try block and enter the catch but it seems I'm wrong:

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
#include <iostream> 

class Copyable
{
public:
	Copyable(){}
	~Copyable()
	{
		std::cout << "destroyed!\n";
	}
	Copyable(const Copyable& other)
	{
		std::cout << "copied!\n";
	}
}; 

int main()
{
	try
	{
		throw Copyable();
	}
	catch (const Copyable& notCopied)
	{
		std::cout << "Object Caught By Reference\n";
	}
}



$ ./a
Object Caught By Reference
destroyed!



Thanks Bazzy
Last edited on
Topic archived. No new replies allowed.