调用C++析构函数失败

Call in C++ Destructor Fails

本文关键字:失败 析构函数 C++ 调用      更新时间:2023-10-16

我有这个代码:

DManag::~DManag() {
    printf("in destn");
    if(mainConn.IsOpen()) {
        printf("about to closen");
        mainConn.Close();
        printf("closed!n");
    }
    printf("end destn");
}

输出为:in dest n about to close n,仅此而已。

它(mainConn->CDatabase类)在调用close()时似乎无声地失败了。我知道你应该在结束关系后立即关闭关系。但我从其他人那里继承了这段代码,但该程序并没有提供在正确的时间关闭连接的简单方法。Close()和open()调用位于afxdb.h中。

知道它为什么会这样失败吗?谢谢

问题似乎是CDatabase::Close抛出异常并导致析构函数的其余部分被绕过。文档中没有提到这个方法可以抛出,但互联网上的其他使用示例表明它可以。

  • http://www.codeproject.com/KB/database/readdb.aspx
  • http://www.dreamincode.net/forums/topic/211232-cdatabaseopenex-fails-without-exception-in-release-mode/

尝试按以下修改析构函数

DManag::~DManag() {
    printf("in destn");
    if(mainConn.IsOpen()) {
        printf("about to closen");
        try {
          mainConn.Close();
        } catch (CDBException&) {
          print("exception occurredn");
        }
        printf("closed!n");
    }
    printf("end destn");
}