Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use shared_ptr or return unique_ptr.get()?

Tags:

c++

mysql

I have a class with a pointer to a MySQL connection. It only makes sense for this pointer and connection to be constant. However, other classes need the connection so one way of dealing with this is to have the class be

class A {
     std::unique_ptr < sql::Connection > conn;

   public:
     const sql::Connection* getConnection ();
}

Or variants of this (like returning a reference or adding const at different places in the declaration of conn. The implementation of getConnection is like

const sql::Connection* A::getConnection() {
  return conn.get();
} 

I am wandering however if I should be using instead std::shared_ptr and returning a copy of the pointer. In which scenario would one choose either approach?

like image 281
Reimundo Heluani Avatar asked Jan 23 '26 20:01

Reimundo Heluani


2 Answers

If your application is designed in a way that can be proven that an SQL connection cannot be used after an instance of your A object goes out of scope and gets destroyed, then using a unique_ptr, and obtaining the underlying pointer using get(), is sufficient.

If, on the other hand, it's possible that there might be a need to use the connection after this A object is destroyed, then the unique_ptr would obviously not be sufficient, and a shared_ptr is in order, here.

There are some other possibilities to consider. For example, having an instance of the A class itself being dynamically allocated, and using a std::shared_ptr<A> to refer to it, in places where it's needed; this proving, by contract, that a given A remains in existence as long as the underlying SQL connection is needed. In such cases, the unique_ptr won't itself have much of a value-added. However, it might make sense to take this approach if A implements some value-added functionality on top of the underlying SQL connection.

like image 104
Sam Varshavchik Avatar answered Jan 25 '26 11:01

Sam Varshavchik


If your application is multi_threaded, opening multiple instances of the database connection is preferable and hence using std::unique_ptr in each instance. This will avoid bottlenecks during sharing of database resources.

like image 33
seccpur Avatar answered Jan 25 '26 10:01

seccpur