0

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");
    }
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • 1
    You can use it with any method that satisfies the function signature, and no others. Specifically,, an instance method requires an instance, which you can't supply via `atexit()`. You might have to write a thunk. – user207421 Apr 15 '22 at 10:11
  • that not how you pass member function pointer, try this https://stackoverflow.com/questions/2402579/function-pointer-to-member-function , and or generay search for member function pointer – nullqube Apr 15 '22 at 10:13
  • 3
    Why do you need this? Why can't you call the function in the destructor? – user17732522 Apr 15 '22 at 10:13

1 Answers1

0
  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;
}
wohlstad
  • 12,661
  • 10
  • 26
  • 39