#include <stdio.h>

class Error {
    int code;
public:
    Error(int c) : code(c) {}
    ~Error() { printf("  destructor of Error %d\n", code); }
    int Code() const { return code; }
};

void throw_object() { throw Error(1); }
void throw_new() { throw new Error(2); }

void throw_local()
{
    Error e(3);
    throw &e;                   /* e dies during unwinding */
}

void attempt(void (*f)())
{
    try {
        f();
    }
    catch (const Error *ex) {
        printf("  caught a pointer\n");
        if (f == throw_new) {
            printf("  code %d\n", ex->Code());
            delete ex;          /* nobody else will */
        }
    }
    catch (const Error& ex) {
        printf("  caught an object, code %d\n", ex.Code());
    }
}

int main()
{
    printf("throw Error(1):\n");
    attempt(throw_object);
    printf("throw new Error(2):\n");
    attempt(throw_new);
    printf("throw &e:\n");
    attempt(throw_local);
    return 0;
}
