Explicit destructor call in a signal handler

I have a destructor that does some necessary cleanup (it kills processes). It should start even when SIGINT is sent to the program. Currently my code is as follows:

typedef boost::shared_ptr<PidManager> PidManagerPtr
void PidManager::handler(int sig)
{
  std::cout << "Caught SIGINT\n";
  instance_.~PidManagerPtr();  //PidManager is a singleton
  exit(1);
}
//handler registered in the PidManager constructor

This works, but there seem to be many warnings against explicitly calling the destructor. Is it right to do this in this situation, or is there a “more correct” way to do this?

+3
source share
6 answers

It turns out that doing it was very bad. The amount of strange things going on is huge.

What's happened

shared_ptr use_count . PidManager, PidManager. shared_ptr (~ PidManager()) use_count . , GMan, exit(), PidManagerPtr_, use_count 0 PidManager. , PidManager , use_count 0, .

, instance_.reset() . 1. - shared_ptr PidManager. shared_ptr , exit(). instance_, reset(), PidManager.

shared_ptrs Meyers Singleton. :

void handler(int sig)
{
     exit(1);
}

typedef PidManager * PidManagerPtr
PidManagerPtr PidManager::instance()
{
    static PidManager instance_;
    static bool handler_registered = false;
    if(!handler_registered)
    {
        signal(SIGINT,handler);
        handler_registered = true;
    }
    return &instance_;
 }

exit PidManager_, . , PidManager .

+2

, . ( !)

auto_ptr, release() . scoped_ptr, reset().

, 99% , exit() . ( .) , exit() atexit().

, - atexit hook:

void release_singleton(void)
{
    //instance_.release();
    instance_.reset();
}

// in main, probably
atexit(release_singleton);
+5

, . . .

+2

. - (, volatile bool), , , , / .

, , , - , , . ( , , )

, boolean, , ( , ), - . , socketpair() () ( - ) ; , , , .

+1

( ) delete .

E. I think your PidManagerPtr actually points to a dynamically allocated object ... But does not raise :: shared_ptr actually clears the redistribution? Therefore, this should be sufficient:

instance_ = 0;

?

0
source

Just call reset () on shared_ptr and it will delete your instance for you.

0
source

Source: https://habr.com/ru/post/1722819/


All Articles