Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3_bind_text SQLITE_STATIC vs SQLITE_TRANSIENT for c++ string

Tags:

c++

sqlite

I have a method that returns a c++ std::string, and then I convert it to a c_str() before passing it into sqlite3_bind_text. My question is, should this be using SQLITE_STATIC or SQLITE_TRANSIENT?

sqlite3_bind_text(insertStatement, 0, suspect->GetIpString().c_str(), -1, SQLITE_STATIC);
// Do some stuff in same function then sqlite3_step

The documentation for sqlite3_bind_text says,

The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and sqlite3_bind_text16() is a destructor used to dispose of the BLOB or string after SQLite has finished with it. The destructor is called to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), sqlite3_bind_text(), or sqlite3_bind_text16() fails. If the fifth argument is the special value SQLITE_STATIC, then SQLite assumes that the information is in static, unmanaged space and does not need to be freed. If the fifth argument has the value SQLITE_TRANSIENT, then SQLite makes its own private copy of the data immediately, before the sqlite3_bind_*() routine returns.

GetIpString returns an std::string, but will that string continue to exist after the call if I don't explicitly make a copy of it? Also, is it safe to use .c_str() without SQLITE_TRANSIANT in general? I know SQLITE_TRANSIENT would be the safe choice, but I want to avoid the copy/performance hit if it isn't needed since this query is going to get run a lot.

like image 861
PherricOxide Avatar asked Apr 16 '13 17:04

PherricOxide


1 Answers

In your case, the string object returned by GetIpString() is likely to get destructed before the query gets executed and finalized, so you should SQLITE_TRANSIENT.

Generally, you should not bother about temporary copies unless you have actual performance problems that you have measured to be caused by this.

like image 109
CL. Avatar answered Sep 28 '22 03:09

CL.