DirectWrite:使用IDWriteTextLayout :: GetMetrics时可能发生内存泄漏

时间:2016-05-20 14:36:26

标签: c++ windows com visual-studio-2015 directwrite

似乎IDWriteTextLayout::GetMetricsIDWriteFactory内的COM引用计数器增加2,但IDWriteTextLayout对象在销毁时根本不会减少它。因此,IDWriteFactory对象不会被销毁。我是对的,这是一个错误吗?

以下是代码段:

#define NTDDI_VERSION NTDDI_VISTA
#define _WIN32_WINNT _WIN32_WINNT_VISTA

#include <windows.h>
#include <dwrite.h>

#include <conio.h>
#include <iostream>

#pragma comment(lib, "Dwrite.lib")

using namespace std;

template<class Interface>
inline void SafeRelease(Interface **ppInterfaceToRelease)
{
    if (*ppInterfaceToRelease != nullptr) {
        (*ppInterfaceToRelease)->Release();
        (*ppInterfaceToRelease) = nullptr;
    }
}

void test(unsigned int);

int wmain(void)
{
    try {
        test(1);
        test(2);
    } catch (HRESULT) {
        cout << "EXCEPTION" << "\n";
    }

    _getch();
}

void test(unsigned int testId)
{
    IDWriteFactory*    factory    = nullptr;
    IDWriteTextFormat* textFormat = nullptr;
    IDWriteTextLayout* textLayout = nullptr;;

    DWRITE_TEXT_METRICS textMetrics;

    auto checkIfError = [&textFormat, &textLayout, &factory](HRESULT hr) -> void {
        if (FAILED(hr)) {
            SafeRelease(&textFormat);
            SafeRelease(&textLayout);
            SafeRelease(&factory);
            throw hr;
        }
    };

    checkIfError(DWriteCreateFactory(
        DWRITE_FACTORY_TYPE_ISOLATED,
        __uuidof(IDWriteFactory),
        reinterpret_cast<IUnknown**>(&factory)
    ));

    checkIfError(factory->CreateTextFormat(
        L"Calibri",
        nullptr,
        DWRITE_FONT_WEIGHT_LIGHT,
        DWRITE_FONT_STYLE_NORMAL,
        DWRITE_FONT_STRETCH_NORMAL,
        16.f,
        L"en-US",
        &textFormat
    ));

    checkIfError(factory->CreateTextLayout(
        L"test",
        4,
        textFormat,
        0,
        0,
        &textLayout
    ));

    if (testId == 2) {
        checkIfError(textLayout->GetMetrics(&textMetrics));
    }

    textFormat->Release();
    textLayout->Release();

    long counter = factory->Release();
    cout << "TEST#: " << testId << ", Counter = " << counter << "\n";
}

执行结果:

  

TEST#:1,Counter = 0
  测试#:2,计数器= 2

平台:带有平台更新的Windows 7 x64 SP1 编译器:Visual Studio 2015 Update 1。

0 个答案:

没有答案