程序退出时没有调用我的析构函数。该对象是一个单身人士,也许我错过了什么?
这是头文件和cpp文件:
#ifndef MYSQLCONNECTOR_H
#define MYSQLCONNECTOR_H
/* Standard C++ headers */
#include <iostream>
#include <string>
/* MySQL Connector/C++ specific headers */
#include <driver.h>
#include <connection.h>
#include <statement.h>
#include <prepared_statement.h>
#include <resultset.h>
#include <metadata.h>
#include <resultset_metadata.h>
#include <exception.h>
#include <warning.h>
class MysqlConnector {
private:
static bool instanceFlag;
static MysqlConnector* mysqlConnector;
MysqlConnector() {
};
public:
static sql::Driver *driver;
static sql::Connection *conn;
static MysqlConnector* getInstance();
virtual ~MysqlConnector() {
instanceFlag = false;
conn->close();
delete conn;
std::cout << "called" << std::endl;
};
private:
};
#endif /* MYSQLCONNECTOR_H */
和cpp文件
#include "MysqlConnector.h"
using namespace std;
using namespace sql;
bool MysqlConnector::instanceFlag = false;
MysqlConnector* MysqlConnector::mysqlConnector = NULL;
MysqlConnector* MysqlConnector::getInstance() {
if (!instanceFlag) {
mysqlConnector = new MysqlConnector();
instanceFlag = true;
try {
driver = get_driver_instance();
/* create a database connection using the Driver */
conn = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* turn off the autocommit */
conn -> setAutoCommit(0);
/* select appropriate database schema */
conn -> setSchema("exchange");
} catch (SQLException &e) {
cout << "ERROR: SQLException in " << __FILE__;
cout << " (" << __func__ << ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << ")" << endl;
if (e.getErrorCode() == 1047) {
cout << "\nYour server does not seem to support Prepared Statements at all. ";
cout << "Perhaps MYSQL < 4.1?" << endl;
}
} catch (std::runtime_error &e) {
cout << "ERROR: runtime_error in " << __FILE__;
cout << " (" << __func__ << ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what() << endl;
}
return mysqlConnector;
} else {
return mysqlConnector;
}
}