I am trying to create a very simple and simple connection pool using the libpqxx library. I am completely new to C ++ and still very confused by pointers and links. The behavior of the class is very simple: to have a vector with some initialized connection and pop, and click the connections on the vector when they are needed. The code has many errors due to poor implementation of pointers and references. Could you give me some advice?
EDIT: I managed to fix all the compilation errors. This gives me a segmentation error 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; }
source share