// File: eh14.cpp - Unwinding the stack
#include <iostream>
#include <string>
using namespace std;
class thing
{
string name;
public:
thing(string arg = ""); // default ctor
thing(const thing& t); // copy ctor
~thing();
};
thing::thing(string arg) : name(arg)
{
try {
if (name == "Satan") throw name;
}
catch (int x) {
cerr << "I caught an int " << x << " and went home\n";
abort();
}
cout << "thing: " << name << " successfully constructed\n";
}
thing::thing(const thing& t) : name(t.name)
{
cout << "thing: " << name << " successfully copy constructed\n";
}
thing::~thing()
{
cout << "destructor called for thing " << name << endl;
}
void funk(const string& n);
int main()
{
string fred("Fred");
string mabel("Mabel");
string sam("Sam");
string sarah("Sarah");
string satan("Satan");
string harry("Harry");
try
{
funk(fred);
funk(mabel);
thing aFriend(sam);
thing aFriendClone(aFriend);
thing* pthing = new thing(sarah);
funk(satan);
thing harry(harry);
}
catch(const string& S)
{
cerr << "I caught " << S << endl;
}
cerr << "*** End of Program ***\n";
return 0;
}
void funk(const string& n)
{
try {
thing object(n);
}
catch (double d) {
cout << "Caught a double: " << d << "\n";
abort();
}
}
***** Program Output *****
thing: Fred successfully constructed destructor called for thing Fred thing: Mabel successfully constructed destructor called for thing Mabel thing: Sam successfully constructed thing: Sam successfully copy constructed thing: Sarah successfully constructed destructor called for thing Sam destructor called for thing Sam I caught Satan *** End of Program ***
What guidelines should you follow to attempt to avoid a memory leak?