3 ms·
Running code when exiting scope is the key to many a things that would be useful, cool, or both. You can simulate some of the cases with a for loop. Other than
by yason 12y ago
Running code when exiting scope is the key to many a things that would be useful, cool, or both. You can simulate some of the cases with a for loop. Other than that, you're out of luck unless you're willing to bite the bullet of compiler-specific features.
If we forget about destructors and think about memory management only then (except for objects that are returned back) allocations could be done on the stack if only the stack was big enough. I think Linux could actually grow stack dynamically but it's usually limited to some minor size.
Thus, I've sometimes emulated that with a chunk of heap-allocated memory that I use for carving new allocations one after another. Then, in some reasonable point in the execution I just reset the cursor back to the start of the big chunk, effectively "freeing" all allocations done by the functions called downwards from that point. It wastes memory but it's convenient as you basically have alloca() that uses heap. But you still need to manage any malloc()'d memory by yourself.
Writing a simple garbage collector working on raw allocations is feasible, too, especially if you use the above heap allocated stack to limit the amount of longer-living allocations you do on the gc heap, and if you have a spot in the program that can stand a slight delay when the gc runs.