我已经编写了以下代码,并且可以正常工作,但是当我运行valgrind来检查泄漏时,就会出现大量泄漏。不知道我在做什么错。
有人请帮助我了解我在做什么错吗?
我的辛格尔顿班:
标题:SampleClass.h
#ifndef SAMPLECLASS_H
#define SAMPLECLASS_H
struct sqlite3;
class SampleClass
{
private:
static SampleClass *m_pHandle;
sqlite3 *m_pSqlDb;
public:
static SampleClass* getHandle() {
if (!m_pHandle)
{
m_pHandle = new SampleClass();
}
return m_pHandle;
}
static void deleteHandle()
{
delete m_pHandle;
m_pHandle = nullptr;
}
void setDatabase(const sqlite3 *psqldb)
{
if (psqldb)
{
m_pSqlDb = const_cast<sqlite3*>(psqldb);
}
else {
// print error
}
}
private:
SampleClass() : m_pSqlDb(nullptr) {}
~SampleClass() { m_pSqlDb = nullptr; }
SampleClass(const SampleClass&) = delete;
SampleClass& operator=(const SampleClass&) = delete;
SampleClass(SampleClass&&) = delete;
SampleClass& operator=(SampleClass&&) = delete;
};
#endif // SAMPLECLASS_H
实施:SampleClass.cpp
#include "SampleClass.h"
SampleClass* SampleClass::m_pHandle = nullptr;
我的驱动程序:Test.cpp
#include "SampleClass.h"
#include <sqlite3.h>
int main()
{
sqlite3 *mydb;
const int retStatus = sqlite3_open_v2("./CPMDB_M100.db", &mydb, SQLITE_OPEN_READWRITE, nullptr);
SampleClass::getHandle()->setDatabase(mydb);
SampleClass::deleteHandle();
return 0;
}
在我的实际实现中,我得到了如下的泄漏摘要。
> LEAK SUMMARY:
> ==32074== definitely lost: 0 bytes in 0 blocks
> ==32074== indirectly lost: 0 bytes in 0 blocks
> ==32074== possibly lost: 0 bytes in 0 blocks
> ==32074== still reachable: 82,680 bytes in 75 blocks
> ==32074== of which reachable via heuristic:
> ==32074== length64 : 9,968 bytes in 73 blocks
如果我删除main()中的deleteHandle()调用,那么所有丢失的块字节都将归入“仍然可访问”类别。
LEAK SUMMARY:
==32095== definitely lost: 872 bytes in 1 blocks
==32095== indirectly lost: 9,016 bytes in 71 blocks
==32095== possibly lost: 0 bytes in 0 blocks
==32095== still reachable: 72,784 bytes in 2 blocks
==32095== of which reachable via heuristic:
==32095== length64 : 80 bytes in 1 blocks
要编译的命令:
g++ -c -std=gnu++11 Test.cpp
g++ -c -std=gnu++11 SampleClass.cpp
g++ -o Test Test.o SampleClass.o -L/usr/include -lsqlite3
谢谢
答案 0 :(得分:0)
您没有使用sqlite3_close_v2
关闭SQL数据库。