2

我尝试使用 COM 在我的程序中实现一个简单的 FileOpenDialog。但我注意到,当使用 FileOpenDialog 多次成功调用选择文件时,发生了内存泄漏。我决定从 msdn 复制这个确切的例子,但是如果我在这个例子中添加一个循环,即像这样:

#include <windows.h>
#include <shobjidl.h> 

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED |
        COINIT_DISABLE_OLE1DDE);
    while(true)
    {
        IFileOpenDialog* pFileOpen;

        // Create the FileOpenDialog object.
        hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
            IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen));

        if (SUCCEEDED(hr))
        {
            // Show the Open dialog box.
            hr = pFileOpen->Show(NULL);
            // Get the file name from the dialog box.
            if (SUCCEEDED(hr))
            {
                IShellItem* pItem;
                hr = pFileOpen->GetResult(&pItem);
                if (SUCCEEDED(hr))
                {
                    PWSTR pszFilePath;
                    hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);

                    // Display the file name to the user.
                    if (SUCCEEDED(hr))
                    {
                        MessageBox(NULL, pszFilePath, L"File Path", MB_OK);
                        CoTaskMemFree(pszFilePath);
                    }
                    pItem->Release();
                }
            }
            pFileOpen->Release();
        }
    }
    CoUninitialize();
    return 0;
}

每次我选择一个文件时,进程内存仍然会增加。我不明白为什么重复调用此代码会导致内存泄漏。

![在此处输入图像描述

4

1 回答 1

1

Deleaker 分析的代码,比较了快照,确实有很多泄漏(见下图)。

同时,代码本身是干净的(尽管避免显式Release()调用总是一个好主意:智能指针是我们的好朋友)。

作为一种解决方法,我将使用单个IFileOpenDialog.

泄漏

于 2020-04-25T10:08:26.783 回答