What is “exception vomiting”?

Viewed 760

Recently on CodeReview.SE, I came across an answer which talks about a technique called “exception vomiting”. Apparently this trick is used to exploit that exceptions have to be implemented in a thread-safe manner independent of whether the compiler supports thread_local variables.

I paste part of this answer below:

There's an existing technique which is not dissimilar referred to as "exception vomiting". Observe:

void f(void(*p)()) {
    p();
}
template<typename F> void real_f(F func) {
    try {
        throw func;
    } catch(...) {
        f([] {
            try {
                throw;
            } catch(F func) {
                func();
            }
        });
    }
}

This abuses the fact that the compiler must provide a thread-local stack for complex objects for use as exception storage, regardless of their support for other thread local features, and therefore enjoys much broad compiler support. The most obvious drawbacks are a) it's horrible, and b) it's limited to stack semantics.

My question is, how does that trick actually work and is it “safe”?

1 Answers
Related