2014-04-12 50 views
0

打交道时,我的方法帮:分段故障与连接对象

bool PGConnection::connect() { 
    try 
    { 
     conn = new pqxx::connection(
          "user=temp " 
          "host=xxxx " 
          "password=xx " 
          "dbname=temp"); 
    } 
    catch (const std::exception &e) 
    { 
     std::cerr << e.what() << std::endl; 
     return false; 
    } 
    return true; 
} 

//Disconnect from db 
bool PGConnection::disconnect() { 
     if (conn->is_open()) { 
      std::cout<<"try disconnect"<<std::endl; 
      conn->disconnect(); 
      return true; 
     } 
    return false; 
} 

PGConnection::~PGConnection() { 
    if (conn != NULL) { 
     delete conn; 
    } 
} 

当断开或类的析构函数被调用时,它会导致segmantation故障。 (当我注释掉断开部分低于它发生的时候调用析构函数)。

int main() { 
PGConnection pgConn("xxx","xxx"); 
pgConn.connect(); 
pgConn.disconnect(); 
return 0; 
} 

gdb with disconnect() called

Program received signal SIGSEGV, Segmentation fault. 
0x00007ffff7ba4852 in pqxx::connection_base::is_open() const() from /usr/lib/libpqxx-3.1.so 
(gdb) bt 
#0 0x00007ffff7ba4852 in pqxx::connection_base::is_open() const() from /usr/lib/libpqxx-3.1.so 
#1 0x00000000004019d3 in PGConnection::disconnect (this=0x7fffffffe600) at pgconnection.cpp:42 
#2 0x000000000040269e in main() at main.cpp:8 
(gdb) frame 2 
#2 0x000000000040269e in main() at main.cpp:8 
8  pgConn.disconnect(); 
(gdb) print pgConn 
$1 = {conn = 0x3} 

gdb with out calling disconnect

(gdb) bt 
#0 0x00007ffff7ba5fdb in pqxx::connection_base::close()() from /usr/lib/libpqxx-3.1.so 
#1 0x0000000000401d3e in pqxx::basic_connection<pqxx::connect_direct>::~basic_connection (this=0x3, 
    __in_chrg=<optimized out>) at /usr/include/pqxx/basic_connection.hxx:74 
#2 0x0000000000401a3d in PGConnection::~PGConnection (this=0x7fffffffe600, __in_chrg=<optimized out>) 
    at pgconnection.cpp:57 
#3 0x00000000004026a3 in main() at main.cpp:11 
(gdb) frame 2 
#2 0x0000000000401a3d in PGConnection::~PGConnection (this=0x7fffffffe600, __in_chrg=<optimized out>) 
    at pgconnection.cpp:57 
57   delete conn; 
(gdb) print conn 
$1 = (pqxx::connection *) 0x3 
(gdb) 

回答

2

很难说没有看到的构造方法PGConnection。特别是,构造函数应该始终设置为conn=NULL

我还建议,目前说

if (conn->is_open()) { 

该行应改为

if (conn && conn->is_open()) { 

我强烈怀疑你conn成员没有被正确初始化。

更好的做法是重新设计班级,这样如果可以的话,您完全不需要使用newdelete。如果你这样做,这将是解决问题的更好方法。 PGConnection不存在很多原因,除非它要连接到某个东西,所以构造函数还可以包含代码以实例化一个pqxx::connection

+0

heh。我是怎么错过的。太棒了!我没有在构造函数中将它赋值为NULL。 – yet