Exception Throwing

Consider the following 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <stdexcept>

using namespace std;


class Speaker
{
private:
	string word_;
public:
	Speaker(const string& s) : word_(s) 
        { cout << "Speaker Created"<<word_<< endl; }

	Speaker(const Speaker& s)
	{
		word_ = s.word_;
		cout << "Copy Constructor of Speaker called" << endl;
	}
   ~Speaker() { cout << "Speaker Destroyed " << word_ << endl; }
};

void Leak();

int main()
{
	try
	{
		Speaker s("In Try Block");
		Leak();
	}
	catch(const exception& e)
	{
		cout << e.what() << endl;
	}
	catch(const Speaker&)
	{
		cout << "Speaker caught" << endl;
	}

	return 0;
}

void Leak()
{
	srand(time(0)); //  start seed for random output

	Speaker spk {"On Stack"};
	Speaker* sp = new Speaker{"On Heap"};

	if(rand() % 2) throw(*sp); 
	else           throw runtime_error("runtime_error occured");

	cout << "Leak Function finished" << endl;
	delete sp;
}


Possible Outputs :
1.________________________________________
Speaker Created In Try Block
Speaker Created On Stack
Speaker Created On Heap
Copy Constructor of Speaker called
Speaker Destroyed On Stack
Speaker Destroyed In Try Block
Speaker caught
Speaker Destroyed On Heap

2.________________________________________
Speaker Created In Try Block
Speaker Created On Stack
Speaker Created On Heap
Speaker Destroyed On Stack
Speaker Destroyed In Try Block
runtime_error occured

Questions :

1.Why in 1st Output the "sp" is deleted but doesn't print that "Leak function
finished" ? ...apparently in the 2nd Output, the lines after throw the code just
doesn't even reach there.

2.Why is the copy constructor of "Speaker" called ? I'm throwing by value and catching by refference.
(line 38)
(Removing the refference of "Speaker" in the catch statement will call the copy constructor 2 times)

Thank You
Last edited on
1. What gets destructed is a temporary copy of *sp ("Copy Constructor of Speaker called"), not *sp itself.
I didn't think that a copy must always be made . How can I pass objects without being copied ?
Does this apply to C++11 as well ?
(Afterwards I'll mark it as solved.)
Thanks
Last edited on
How can I pass objects without being copied ?
Pss by reference or pass a pointer to it.
However in C++ it is advised to throw by value and catch by reference.
Throwing reference or pointer will either cause Undefined Behavior (if original is stack allocated) or force you to manually manage memory (which you should avoid in modern C++).

Does this apply to C++11 as well ?
In C++11 you can try to use move semantics (Which would be almost as fast as pointer/reference passing if you are employing PIMPL idiom).
Topic archived. No new replies allowed.