c++ - 如何在atexit()中析构实例

标签 c++

我希望始终在程序结束之前调用实例 (proc) 的析构函数,尤其是在return 1之后em> 或 main 中的 exit()

我找到了C++函数atexit(),但它需要指向没有参数的void函数的指针,因此下面的代码无法编译。 请问我该如何解决?

我的实例的析构函数需要 MySQL 连接。

#include <WinSock.h>
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <mysql.h>
#include <string>

// Declarations for Mysql DB

using namespace std;

class Process {
  public:
     ~Process();
};

Process::~Process ()
{
    // Interaction with DB
}

int main(void) 
{
  // Join to DB

  atexit(proc.~Process); // Call desctructor of instance proc before program ends

  Process proc;

  // App code

  return 0;
}

最佳答案

proc 具有自动持续时间,即退出 main 时,它将自动销毁(并调用析构函数) - 您不需要 atexit 业务..

除非@Rob 在下面提到,你在代码中的某个地方调用 exit() ...如果是这样的话,那么你必须分配 Process堆,提供一个 atexit 可以调用的函数,该函数知道该实例,并在那里删除它...

关于c++ - 如何在atexit()中析构实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8185768/

相关文章:

c++ - C++ 一行中的多个命名空间

c++ - 具有通用模板化基类型的 STL 容器,接受派生类型

c++ - 如何检测和处理算法中不受支持的语言环境?

c++ - 在 C++ 中将指针转换为数组

c++ - 同时读/写是否会导致数据竞争以外的任何其他问题?

C++ 软件设计选项,类关系

c++ - 如何在STL中强制内联单个成员函数?

c - fprintf() 函数无法将数据持久化到文件; fflush() 函数后面必须跟着?

c++ - 使用来自共享对象的应用程序对象

c++ - 什么时候使用表达式的类型(不是类别)?