Listing 12
#include <memory>
#include <stdlib.h>
#include <new>
#include <iostream>
using std::tr1::shared_ptr;
using std::cout; using std::bad_alloc;
struct S
{ // simple struct
S() { cout << "S object constructed\n"; }
~S() { cout << "S object destroyed\n"; }
};
static bool new_should_fail;
void *operator new(size_t sz)
{ // fails on demand
if (new_should_fail)
{ // reset, so subsequent calls succeed
new_should_fail = false;
throw bad_alloc();
}
return malloc(sz);
}
void operator delete(void *ptr)
{ // complement to operator new
free(ptr);
}
int main()
{ // demonstrate exception safety
S *sptr = new S;
new_should_fail = true;
shared_ptr<S> sp;
try
{ // make sure we can catch exceptions
sp.reset(sptr);
}
catch(const bad_alloc&)
{ // got one!
cout << "Caught bad_alloc\n";
}
return 0;
}