jeudi 15 août 2019

How to call destructor of object on termination with Ctrl-c?

I have an object which I want to guarantee will be destructed even if the program is terminated with Ctrl-c.

I have tried doing this using a signal handler which resets a unique pointer but I have been told that std::unique_ptr::reset is forbidden to be used in a signal handler.

std::unique_ptr<MotionControl> mc;

void signal_handler(int signal_num) { 
    // destruct MotionControl object and delete pointer
    mc.reset();
    // terminate program   
    exit(signal_num);   
} 

int main(int argc, char** argv)
{
    signal(SIGINT, signal_handler);

    try {
        std::string deviceName("/dev/ttyACM0");
        mc = std::unique_ptr<MotionControl>(new MotionControl(deviceName, 119, 65, 10));
        ...
    }
    ...
}

Therefore, how can I go about doing this?

Aucun commentaire:

Enregistrer un commentaire