I am trying to develop a very simple and straightforward connection pool using the libpqxx library. I am quite new to c++ and still very confused with pointers and referencing. The behaviour of the class is very simple: have a vector with some initialized connection, and pop and push connections onto the vector when they are needed. The code has many errors due to the bad implementation of pointers and referencing. Can you please give me some hints?
EDIT: I managed to fix all compilation errors. It is giving me a segmentation fault when I run the main function.
class DbPool {
public:
pqxx::result runQuery(const string& query) {
connection *conn = getCon();
work trans(*conn);
result res = trans.exec(query);
trans.commit();
releaseCon(conn);
return res;
}
DbPool(uint32_t max_cons) {
for (uint32_t i = 0; i < max_cons; i++) {
connection* con = createCon();
m_freeCons.push_back(shared_ptr < connection > (con));
}
}
private:
connection * createCon() {
connection * conn =
new connection(
"user='ak' password='rootpassword' dbname='bips_office' hostaddr='127.0.0.1' port='5432'");
return conn;
}
void releaseCon(connection *con) {
m_freeCons.push_back(shared_ptr < connection > (con));
}
connection* getCon() {
shared_ptr < connection > conn = *(m_freeCons.end() - 1);
m_freeCons.pop_back();
return conn.get();
}
vector<shared_ptr<connection> > m_freeCons;
};
int main(int argc, char *argv[]) {
DbPool *pool = new DbPool(5);
result res = pool->runQuery("SELECT COUNT (*) from captures");
return 0;
}