Hacker News new | past | comments | ask | show | jobs | submit login

I use a stack allocator that knows about setjmp()/longjmp(), functions, scopes, and destructors. (Destructors are a function pointer type in my code.)

Basically, you tell the stack allocator to store a jmp_buf, then you setjmp() on it. Then keep going.

For a function, a special destructor is used as a marker. Same with scopes.

The same is also true of a setjmp() destructor, which is actually what activates longjmp().

The stack allocator should have three functions to unwind itself until it reaches the end of the next scope, function, or jmp, respectively.

Then, when you need an exception, or to exit a function or scope, you call the correct stack allocator function to clean up everything to that point. Then you return or whatever.

This can run arbitrary code on cleanup for an item if you write a "destructor" with that arbitrary code. For example, one idea I had was to use the stack allocator to ensure a mutex or other lock was always released. This would be done by storing a pointer to the mutex and writing a "destructor" that unlocks the mutex when given a pointer to the mutex. Boom. Scope-based mutex unlocking.

Makes sense?




Thanks for that. I think I'll stick to Rust! But good luck!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: