sqlite3_column_text非常慢 (C) 并产生内存泄漏

sqlite3_column_text is very slow (C) and creates memory leak

本文关键字:内存 泄漏 text column 非常 sqlite3      更新时间:2023-10-16

我正在用C++编写一个程序,我使用SQLite。我的代码:

if (s == SQLITE_ROW) {
    int id = 0;
    string stem;
    id = sqlite3_column_int (selectStmt, 0);
    stem = std::string(
               reinterpret_cast<const char*>(sqlite3_column_text (selectStmt, 1))
           );
    if (id > 0)
        StemClass *st = new StemClass(id, stem);
    row++;      
}

sqlite3_column_text非常慢,并且会产生内存泄漏。

  • 我怎样才能避免这种情况?
  • 还有别的办法吗?

为了提高速度,您可以尝试:

auto const p(reinterpret_cast<const char*>(sqlite3_column_text (selectStmt, 1)));
::std::string stem(p, sqlite3_column_bytes(selectStmt, 1));

对于泄漏,请使用智能指针,例如 ::std::shared_ptr::std::unique_ptr 。可能是你的new在泄漏。以前,您创建一个空的::std::string实例,然后将新::std::string复制到其中。坏主意。对每个未被智能指针或某些 RAII 方案(如 SCOPE_EXIT)捕获的new表达式都持怀疑态度。