所以我试图构建一个连接到mysql数据库的类,我想在构造函数中连接并捕获异常来处理它们而不是构造类。由于我不会进入的原因,我需要它以这种方式工作。我在SQLConnection.cpp的析构函数中尝试删除指针时发现了错误。这个指针是从MySQL连接器库函数实例化的,我看到的每个教程和示例都在最后删除了它。它对我来说似乎不对,但我无法找到关于该函数的文档,以了解为什么删除存在。此外,当我删除这个相同的指针只是在主要运行一些测试它很好(没有seg错误)。
到目前为止,这是重要的代码
SQLConnection.h
#ifndef SQLCONNECTION_H
#define SQLCONNECTION_H
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
class SQLConnection{
private:
sql::Driver *driver;
const std::string IP;
const std::string user;
const std::string password;
void connect();
public:
sql::Connection *con;
SQLConnection();
SQLConnection(std::string inIP, std::string inUser, std::string inPassword);
~SQLConnection();
};
#endif
SQLConnection.cpp(析构函数中的删除会导致seg错误。当它被取出时它会消失。我会说明为什么我会关注它之后将它全部一起拿出来
#include "SQLConnection.h"
SQLConnection::SQLConnection() = default;
SQLConnection::SQLConnection(const std::string inIP, const std::string inUser, const std::string inPassword)
: IP(inIP), user(inUser), password(inPassword)
{
try
{
connect();
}
catch(...)
{
throw;
}
}
SQLConnection::~SQLConnection(){
if(con != nullptr){
delete con; //CAUSES SEG FAULT, when taken out program runs fine
}
}
void SQLConnection::connect(){
try{
driver = get_driver_instance();
con = driver->connect(IP, user, password);
}
catch (sql::SQLException &e) {
std::cout << "# ERR: SQLException in " << __FILE__;
std::cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << '\n';
std::cout << "# ERR: " << e.what() << '\n';
std::cout << "# ERR: MySQL error code: " << e.getErrorCode() << '\n';
}
if(con)
{
std::cout<<"Connected!" << "\n";
}
}
main.cpp
const std::string ip = "tcp://127.0.0.1:3306";
const std::string user = "IncorrectUser";
const std::string password = "IncorrectPass";
SQLConnection con1(ip, user, password);
std::cout << "still going" << '\n';
如果使用不正确的登录凭据运行,则输出
4 line of exceptions from catch block in connect
connected!
still going
segmentation fault (core dumped)
使用正确的凭据一切正常
main.cpp没有类来测试连接工作正常
try{
driver = get_driver_instance();
con = driver->connect(IP, user, password);
}
catch(sql::SQLException &e){
std::cout << e.what() << '\n';
if(con){
std::cout << "connected!" << '\n';
}
delete con;
所以我想我的主要问题是为什么如果构造函数抛出一个异常就不应该说这个类不应该进入&#34;存在&#34;。因此它不应该说连接并在主要结尾处调用它的析构函数导致seg错误?另外如果我需要在构造函数中使用函数级别try catch来解决这个问题,有人可以给我一个关于如何从启动列表中调用成员函数的提示。当我在编译错误之前尝试了这个
member field connect() does not exist