如何释放 googletest ASSERT_THROW 语句中函数使用的资源?

How to free up a resource used by a function in a googletest ASSERT_THROW statement?

在 googletest 中,您可以使用 ASSERT_THROW 来测试某个函数是否会抛出错误。例如

ASSERT_THROW(PhysicalPropertyResource p("other/identifier72652"), InappropriateResourceException);

您将如何显式调用另一种方法来释放 PhysicalPropertyResource 使用的一些内存?通常这样使用:

PhysicalPropertyResource p("other/identifier72652");
p.free();

或者我不应该担心内存泄漏,因为它只是在测试中,因此是良性的。 (这只是我的强迫症,想让 valgrind 完全开心)。

我试过这个:

    ASSERT_THROW(
            PhysicalPropertyResource p("other/identifier72652");
            p.free();
            , InappropriateResourceException);

}

这不会释放内存。

执行多条指令的正确语法是将它们包装在一个块中:

ASSERT_THROW({PhysicalPropertyResource p("other/identifier72652");
              p.free();}, 
            InappropriateResourceException);

然而,这不会帮助它不是抛出的最后一行,因为那样 p.free() 将不会被调用。您可以创建自己的 "assertion"

void shouldThrow() {
    std::unique_ptr<PhysicalPropertyResource> p;
    try {
        p = std::make_unique<PhysicalPropertyResource>("other/identifier72652");
    } catch (const InappropriateResourceException&) {
        if (p) //note that this is not possible if it is really constructor that throws
            p->free(); 
        return; //test succeeded
    } catch (...) {
        if (p)
            p->free();
        FAIL();
    }

    if (p)
        p->free;
    FAIL();
}

注意:如果您正在编写使用 C 库的 C++ 代码,那么最好的解决方案是创建一个 RAII 包装器来处理资源。如果你创建一个包装器 class,它可以释放析构函数中的资源,你永远不会泄漏它们。你甚至可以只为单元测试编写这样的包装器,只是为了避免这种丑陋的类似断言的代码。