Can I use 'atexit()' function with a class method

393 Views Asked by At

I am trying to use the atexit() in C++ with a class method as the parameter. Is this possible or should I try using something else.

void Editor::disableRawMode(){
  if(tcsetattr(STDIN_FILENO, TCSAFLUSH, &this->conf.orig_termios) == -1){
      makeError(ErrorType::RawModeErr, "tcgetattr");
  }
}


void Editor::enableRawMode(){
    if(tcgetattr(STDIN_FILENO, &this->conf.orig_termios) == -1){
        makeError(ErrorType::RawModeErr, "tcgetattr");
    }

    std::atexit(disableRawMode);

    struct termios raw = this->conf.orig_termios;

    raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    raw.c_oflag &= ~(OPOST);
    raw.c_cflag |= (CS8);
    raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
    raw.c_cc[VMIN] = 0;
    raw.c_cc[VTIME] = 1;

    if(tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1){
        makeError(ErrorType::RawModeErr, "tcgetattr");
    }
}
1

There are 1 best solutions below

0
On
  1. The function std::atexit requires a function getting void and returning void.

  2. Passing a method would not work because the this pointer will be missing.

  3. What you can pass to std::atexit can be one of the following: global/static function or a lambda with no capture or parameters.

See the code below:

// NOTE: f could also be a static method in a class.
void f()
{
    // ...
}

int main() 
{
    // option 1:
    std::atexit(f);
    // option 2:
    std::atexit([]() { /* ... */});
    // ...
    return 0;
}