首页 > 解决方案 > 当在作为智能指针的函数参数上使用匹配器时,如何修复 Gmock 测试中的内存泄漏?

问题描述

所以我在一个大的测试代码上有一段代码,不是我写的,但我需要调试一个泄漏:

TEST_F(LeakChecked, PurgeNotify)
{
    AsyncManager asyncManager;
    DataIndexer indexer(*logger_, asyncManager);

    //....

    EXPECT_CALL(
        asyncManager,
        RunAsync(
            AllOf(
                EventType("DataPurged"),
                EventTime(0),
                EventJson(
                    R"({"bucket":"dropped_files","data":{"path":"c:\\foo\\test.exe"},"time":0,"type":"DataPurged"})"),
                EventCoverage()),
            _,
            0,
            0));

    //...

    Mock::VerifyAndClearExpectations(&asyncManager);
}

夹具使用 Windows 的 _CrtMemCheckpoint 和其他函数来检测其析构函数中的内存泄漏。我在那里有大约 6 处泄漏,在添加了 _CrtSetBreakAlloc 来中断它们之后,结果发现它们都指向前面提到的 EXPECT_CALL 宏。

RunAsync 是一个方法,其第一个参数是 std::shared_ptr 但没有任何泄漏似乎表明指向的对象已泄漏,而是分配发生在 gmock-matchers.h 中,它Matcher<T>用 new 分配 a。

在其他线程中,我读到调用 VerifyAndClearExpectations 应该可以工作,但在我的情况下,泄漏仍然存在。

我可以做些什么来修复,或者我应该只是抑制泄漏?

标签: c++memory-leaksgooglemock

解决方案


推荐阅读