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