Search code examples
c++sqliteshared-ptr

Using shared_ptr with sqlite3


I am trying to use shared_ptr to protect the memory leaks that the sqlite3 library is throwing in my application.

I need to translate my plain c++ code to a protected version without doing a huge change. The current state of my code is something like:

sqlite3* db = NULL;
sqlite3_open(dbname.c_str(),   &db );
sqlite3_close( db );

And I have tried:

std::shared_ptr<sqlite3> db(NULL);
sqlite3_close( db.get() );

But I can not translate the open function because it is requesting a sqlite3** parameter that I am not able to emulate with a shared pointer. I have found std::shared_ptr connection(rawConnec, sqlite3_close); but this kind of function have not official documentation or any of example.

I am so blocked, Thank you so much


Solution

  • std::shared_ptr<sqlite3> db(nullptr);
    {
      sqlite3* dbPtr = NULL;
      sqlite3_open(dbname.c_str(),   &dbPtr );
      db.reset(dpPtr, sqlite3_close);
    }
    

    Then once db and all other std::shared_ptrs go out of scope sqlite3_close will be called on your resource.

    However this is a bit of a hack and in the long run you will be much better off with a standard RAII class as is standard C++ practice.