Sign in to follow this  
smart_idiot

Automatic destruction.

Recommended Posts

I want to have a function called after main() exits, but before global objects start getting destroyed. The problem is that I have a bunch of objects stored in a cache, which gets destroyed at the end of the program. Some of the classes use a global mutex object to be able to safely interact with their respective libraries, but it has already been automatically destroyed before I've gotten to destroying the objects that use it. atexit() doesn't seem to do its thing until afterwards. My current idea is to make a dummy object and have an instance of it after each of those global objects, and have the first one to be destroyed call my function in its destructor. This assumes that objects get created in the order they appear, and get destroyed in the reverse order they were created. Would that work, or is there something else I can try? This is C++ incase anyone wasn't sure.

Share this post


Link to post
Share on other sites
That's the sort of behaviour I wrap into an application level singleton or framework functions eg:



BigFeckingSingleton* pSingle;
int iRetVal;

int main( args )
{
initialise( args ); // initialise app singleton
run();
shutdown(); // destroy singleton
return iRetVal;
}


I'd aggregate your global mutex into the singleton, and deal with ctor / dtor order as you normally would. I consider it bad practice to have a cluttered main anyway.

Unless there's any particular reason you want to mess with process cleanup time?

Share this post


Link to post
Share on other sites
Why not just move the current contents of main somewhere else, and have the new main call the old one followed by your "cleanup"?

Share this post


Link to post
Share on other sites
I'd rather not do anything fancy to main; I'm trying to just write a library, not a whole program.

I think instead I'm going to make a global structure to contain those objects, and have its destructor make sure everything gets cleaned up, since that should happen before the structure's memebers get destroyed.

Of course then someone might make their own class that depends on a global object, then they'll have the same problem I'm having now. All well. Then it will be their problem, instead.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this