Boost logo

Boost Users :

From: Oliver Schoenborn (oliver.schoenborn_at_[hidden])
Date: 2005-11-03 13:27:01


> class Connection {
> boost::shared_ptr<MYSQL> m_mysql;
> public:
> void connect() {
> m_mysql.reset(mysql_init(), mysql_close);
> }
> bool isConnected() const { return m_mysql.get() != 0; } };
>
> class ConnectionManager {
> std::map<std::string, Connection> m_connections;
> public:
> static ConnectionManager* instance() {
> static ConnectionManager cm;
> return &cm;
> }
> Connection connection(const std::string& name = "default")
> { return m_connections[name]; }
> };
>
> int main()
> {
> {
> Connection c = ConnectionManager::instance()->connection();
> std::clog << "isConnected " << c.isConnected() << std::endl;
> c.connect();
> std::clog << "isConnected " << c.isConnected() << std::endl;
> }
> Connection c = ConnectionManager::instance()->connection();
> std::clog << "isConnected " << c.isConnected() << std::endl;
>
> return 0;
> }
>
> And the output is:
>
> isConnected 0
> MYSQL* mysql_init()
> isConnected 1
> void mysql_close(MYSQL*)
> isConnected 0
>
> What I don't understand is why shared_ptr calls mysql_close too soon.
> After all still exists a reference to Connection. I mean,
> mysql_close should by called when the ConnectionManager
> singleton is destroyed or am I doing something wrong.

Both c and the map item in ConnectionManager have a shared pointer that
points to the "same" MYSQL object, a null. Then you reset c to point to
something else. This will not reset the shared pointer in ConnectionManager.
Your MYSQL obj gets killed as soon as c goes out of scope.

Oliver

> - -- Filipe Sousa
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.2 (GNU/Linux)
>
> iD8DBQFDalOEbQdNYqwwwCwRAsNLAJ43BSZTCuraPQ2ouFqGoW/2+JDPDgCeOoQ7
> 8ZoF4LDO7vQyrPM/Whtx/O8=
> =iil3
> -----END PGP SIGNATURE-----
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net