class PrivateClass
{
PrivateClass(){}
static PrivateClass Cheat;
};
PrivateClass PrivateClass::Cheat;
The reason I want to do this is so that I can make use of the destructor being called at program end, even if the program ended via an unhandled exception. Now, what I want to know is:
1. Should I even bother making it unconstructable like this? The reason I did was because I saw it as a very bad idea to instantiate more than one of these.
2. Is there a better, platform-independent alternative?
3. Am I doing something wrong or missing something here?
Correct me if I'm wrong, but the whole point of exceptions and destructors is that in an unhandled exception, the destructors WILL be called. Isn't this the whole principle on which RAII is based?
So just do:
1 2 3 4 5 6 7 8
int main() {
struct s {
~s() { //whatever
}
} an_s;
...
...
}
As long as your process doesn't do anything daft like abort. then you'll be fine. I'm also not certain about the different compiler guarantees about destruction of static objects. My intuition says it's a bit of a minefield.
The previous solution is ok, but I think it encourages ignoring exceptions, which I don't like. I was working on reverse engineering a project last year that had a lot of
1 2 3 4
try {
//stuff
} catch (...) {
}
It wasn't fun, and for some of it, once I knew what that section of was supposed to do, I just scraped it, and rewrote it myself.
Thanks for the replies. Unfortunately it's kinda difficult to put a try-catch block in the global scope, especially with a library I can't modify. I think I'm going to do this differently now reading your helpful replies :)
If no matching handler is found in a program, the function terminate() (_except.terminate_) is called. Whether or not the stack is unwound before calling terminate() is implementation-defined.
@L B:
The reason I want to do this is so that I can make use of the destructor being called at program end
Keeping the console open is where I got the idea for this, it looked so amazingly simple that I thought it had to have other uses...I guess I got carried away and started to do things in ways I shouldn't be doing them in. ;)