I searched google and stackoverflow but did not find an answer for my particular usage. There is much good advice regarding raw pointers and the advantage of std::shared_ptr but not related to a std::stack.
I watched Herb Sutters talk on youtube about writing good C++14 code (https://www.youtube.com/watch?v=hEx5DNLWGgA) and one topic is why unique and shared pointers are useful.
So I rewrote my simple db connection pool from raw pointers to std::shared_ptr instead. After I top()/pop() the stack for a connection and interact with the db I push() it back.
With raw pointers in the constructor
Database::Database(const unsigned int connections) {
for (int i = 0; i < connections; ++i) {
try {
auto* dbconn = new pqxx::connection(connectionString);
dbpool.push(dbconn);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
}
}
And later on
auto *D = dbpool.top();
dbpool.pop();
std::string query = "select * from races order by racestart_at desc";
pqxx::nontransaction N(*D);
pqxx::result R(N.exec(query));
dbpool.push(D);
Using shared_ptr in constructor
auto* dbconn = new pqxx::connection(connectionString);
std::shared_ptr<pqxx::connection> s_dbconn(dbconn);
dbpool.emplace(s_dbconn);
And in the program
auto D = dbpool.top();
dbpool.pop();
<query db etc.>
dbpool.push(D);
Are raw pointers as good as shared pointers in this case? I don't see that a raw pointer can go astray that many places.