Skip to content

Instantly share code, notes, and snippets.

@BBBSnowball
Created October 13, 2013 00:56
Show Gist options
  • Save BBBSnowball/6956738 to your computer and use it in GitHub Desktop.
Save BBBSnowball/6956738 to your computer and use it in GitHub Desktop.
Test program for exception thrown in constructor
#include <iostream>
#include <string>
using namespace std;
class PrintLifecycle {
string name;
public:
PrintLifecycle(string name) : name(name) {
cout << "constructor of " << name << endl;
}
virtual ~PrintLifecycle() {
cout << "destructor of " << name << endl;
}
static void* operator new(size_t size) {
void* result = ::operator new(size);
cout << "allocating object of size " << size << " -> " << result << endl;
return result;
}
static void operator delete(void* ptr) {
cout << "deleting memory at " << ptr << endl;
}
};
class Blub : public PrintLifecycle {
PrintLifecycle blub;
public:
Blub(string name) : PrintLifecycle(name), blub("Blub.blub") { }
};
class my_exception : public exception { };
class Foo : public Blub {
PrintLifecycle foo;
PrintLifecycle bar;
public:
Foo() : Blub("Foo"), foo("Foo.foo"), bar("Foo.bar") {
throw my_exception();
}
};
class RaiseException : PrintLifecycle {
public:
RaiseException() : PrintLifecycle("RaiseException") {
throw my_exception();
}
};
class Foo2 : public Blub {
PrintLifecycle foo;
RaiseException exc;
PrintLifecycle bar;
public:
Foo2() : Blub("Foo2"), foo("Foo.foo"), exc(), bar("Foo.bar") {
}
};
int main(int argc, char** argv) {
delete new Blub("blub");
cout << endl;
try {
delete new Foo();
cout << "no exception ?!" << endl;
} catch (my_exception) {
// ignore
}
cout << endl;
try {
delete new Foo2();
cout << "no exception ?!" << endl;
} catch (my_exception) {
// ignore
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment