...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <csetjmp> #include <iostream> static jmp_buf env; struct Counter { static int Instancesinstances; Counter() { ++Instancesinstances; } ~Counter() { --Instancesinstances; } }; int Counter::Instancesinstances = 0; void f() { Counter c; std::cout << "f(): Instances: " << Counter::Instancesinstances << std::endl; std::longjmp(env, 1); } int main() { std::cout << "Before setjmp(): Instances: " << Counter::Instancesinstances << std::endl; if (setjmp(env) == 0) { f(); } else { std::cout << "From longjmp(): Instances: " << Counter::Instancesinstances << std::endl; } std::cout << "After longjmp(): Instances: " << Counter::Instancesinstances << std::endl; } |
Implementation Details
The above code produces the following results when compiled with Clang 3.5 8 for Linux, demonstrating that the undefined behavior in this instance is to fail to destroy the local Counter
instance when the execution of f()
is terminated:
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream> struct Counter { static int Instancesinstances; Counter() { ++Instancesinstances; } ~Counter() { --Instancesinstances; } }; int Counter::Instancesinstances = 0; void f() { Counter c; std::cout << "f(): Instances: " << Counter::Instancesinstances << std::endl; throw "Exception"; } int main() { std::cout << "Before throw: Instances: " << Counter::Instancesinstances << std::endl; try { f(); } catch (const char *E) { std::cout << "From catch: Instances: " << Counter::Instancesinstances << std::endl; } std::cout << "After catch: Instances: " << Counter::Instancesinstances << std::endl; } |
which produces the following output:
...