【发布时间】:2011-03-17 15:01:11
【问题描述】:
我们在课堂上使用 pimpl 成语。 pimpl 结构在包含 pimpl 指针的类中声明,如下所示:
struct MyClassImpl;
friend struct MyClassImpl;
boost::scoped_ptr<MyClassImpl> m_Impl;
pimpl 的实现在一个名为 MyClassImpl.cpp 的单独文件中 例如:
struct MyClass::MyClassImpl
{
QString m_Name;
int m_Type;
double m_Frequency;
int m_DefaultSize;
QVariant m_DefaultValue;
boost::shared_ptr<SomeOtherClass> m_SomeOtherClass;
~MyClassImpl()
{
}
};
在包含 pimpl 指针的类的构造函数中,我会在成员变量初始化列表中有类似
m_Impl(new MyClassImpl())
现在,我们在源代码中启用了内存泄漏检测,如下所示:
// Memory leaks detection in Visual Studio
#if defined (_WIN32) && defined (_DEBUG)
# define _CRTDBG_MAP_ALLOC
# include <crtdbg.h>
# define new new(_NORMAL_BLOCK ,__FILE__, __LINE__)
#endif
我发现当程序退出时,MyClassImpl() struct m_Impl(new MyClassImpl()) 会报告内存泄漏:
..\..\src\MyClass.cpp(29) : {290222} normal block at 0x0B9664E0, 48 bytes long.
Data: <X l V Y@> 58 1C 6C 03 56 00 00 00 00 00 00 00 00 00 59 40
我不明白为什么,因为 m_Impl 是 boost::scoped_ptr 并且 QString、QVariant 和 shared_ptr 都是托管的。有什么想法吗?
【问题讨论】:
-
您确定在调用 exit 之前调用了 MyClass 析构函数吗?
-
如果您想获得有关泄漏的更好信息,请获取 Visual Leak Detector。
-
shared_ptr 可能是引用循环的一部分,并阻止内容被释放。如果没有
SomeOtherClasstho 的定义,就无法判断。 -
那个 QVariant 看起来像是我的罪魁祸首。里面有什么?
-
Sam:是的,我确定调用了 MyClass 析构函数
标签: qt boost memory-leaks pimpl-idiom