Jonathan Wakely wrote:
>> If you want to donate the class under the LGPL, it sounds like something
>> we'd like to have in MySQL++.
>>
>
> I'd be happy to review any patch.
>
Ok, see patch inline below. Hope you find it useful.
It's non-copyable so you can't use it in a container or in a copyable
object.
Joel
Index: lib/scopedconnection.cpp
===================================================================
--- lib/scopedconnection.cpp (revision 0)
+++ lib/scopedconnection.cpp (revision 0)
@@ -0,0 +1,29 @@
+#include "scopedconnection.h"
+
+#include "cpool.h"
+
+namespace mysqlpp {
+
+ScopedConnection::ScopedConnection(mysqlpp::ConnectionPool& pool)
+: pool_(pool), connection_(pool.grab())
+{
+}
+
+ScopedConnection::~ScopedConnection()
+{
+ pool_.release(connection_);
+}
+
+Connection*
+ScopedConnection::operator->() const
+{
+ return connection_;
+}
+
+Connection&
+ScopedConnection::operator*() const
+{
+ return *connection_;
+}
+
+} // end namespace mysqlpp
Index: lib/scopedconnection.h
===================================================================
--- lib/scopedconnection.h (revision 0)
+++ lib/scopedconnection.h (revision 0)
@@ -0,0 +1,54 @@
+#if !defined(MYSQLPP_SCOPEDCONNECTION_H)
+#define MYSQLPP_SCOPEDCONNECTION_H
+
+#include "common.h"
+
+namespace mysqlpp {
+
+#if !defined(DOXYGEN_IGNORE)
+// Make Doxygen ignore this
+class MYSQLPP_EXPORT Connection;
+class MYSQLPP_EXPORT ConnectionPool;
+#endif
+
+/// \brief Grabs a Connection from a ConnectionPool on construction
+/// and releases it back to the pool on destruction, and provides access
+/// to the relevant Connection pointer.
+class MYSQLPP_EXPORT ScopedConnection
+{
+public:
+ /// \brief Standard constructor
+ ///
+ /// Grabs a Connection from the specified pool.
+ ///
+ /// \param pool The ConnectionPool to use.
+ ScopedConnection(ConnectionPool& pool);
+
+ /// \brief Destructor
+ ///
+ /// Releases the Connection back to the ConnectionPool.
+ ~ScopedConnection();
+
+ /// Access the Connection pointer
+ Connection* operator->() const;
+
+ /// Dereference
+ Connection& operator*() const;
+
+private:
+
+ /// No default constructor
+ ScopedConnection();
+ /// Non-copyable
+ ScopedConnection(const ScopedConnection& no_copies);
+ /// Non-copyable
+ const ScopedConnection& operator=(const ScopedConnection& no_copies);
+
+ ConnectionPool& pool_;
+ Connection* const connection_;
+};
+
+} // end namespace mysqlpp
+
+#endif // !defined(MYSQLPP_SCOPEDCONNECTION_H)
+