开发者

pimpl idiom struct memory leak

We are using the pimpl idiom in our classes. The pimpl struct is declared in the class which contains the pimpl pointer like so:

struct MyClassImpl;
friend struct MyClassImpl;
boost::scoped_ptr<MyClassImpl> m_Impl;

The implementation for the pimpl is in a seperate file called MyClassImpl.cpp For example:

    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()
            {
            }
        };

In the constructor of a class that contains a pimpl pointer, I would have in the member variable initialization list something like

m_Impl(new MyClassImpl())

Now, we have enabled memory leak detection in our source code like so:

// 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

I am finding that when the program exits, memory leaks are reported for the 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 

I don't understand why since the m_Impl is a boost::scoped_ptr and the QString, QVariant, and shared_ptr are all managed. Any ideas?


It does look like it should work..

What i find odd is the size of the leak, only 48 bytes.

I'd draw the conclusion that the MyClassImpl struct is freed, but something in it, isn't. Should the entire struct leak, the leak would be a lot bigger than 48 bytes.

But still, I can find no fault in that code.

Get Visual Leak Detector to enhance your debugging, it's free.

http://vld.codeplex.com/


Perhaps instances of MyClass are being freed without being properly deleted? If, for example, they're being allocated somewhere using placement new, then they wouldn't be reported as individually leaking, but neither would they be automatically destructed when their memory was released.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜