简体   繁体   中英

How to run function on ending a C++ Command Line App?

我知道这可能已经在这里有了答案,但基本上我需要在强制关闭命令行时关闭服务器上的会话。

Use a C++ destructor. At the beginning of your main(), define a variable with a session class like below.

class ManageSession
{
public:
   int sessionId;
   ManageSession() {
      sessionId = Connect();
   }
   ~ManageSession()
   {
      Close(sessionId);
   }

   int Connect() {
      // find and connect
      return 42;
   }
   void Close(int id) {
      if (id > 0) {
         id = 0; // close it
      }
   }
};

int main() {
   ManageSession session;

   // do amazing things
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM