为什么Google Test / Mock显示std :: unique_ptr泄漏的模拟对象错误? [英] Why does Google Test/Mock show leaked mock object error by std::unique_ptr?

查看:182
本文介绍了为什么Google Test / Mock显示std :: unique_ptr泄漏的模拟对象错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设有一个 Bar 对象,该对象使用 Foo 对象。所有权是专有的,因此 Bar 获得 Foo 作为 std :: unique_ptr 在其构造函数中。我想使用Google Test框架测试 Bar ,所以我编写了以下代码:

Let's assume that there is Bar object which uses a Foo object. The ownership is exclusive, so Bar gets Foo as a std::unique_ptr in its constructor. I would like to test Bar with Google Test framework, so I made a following code:

using namespace testing;

class Foo
{
  public:
    virtual int F() = 0;
};

class Bar
{
  public:
    Bar(std::unique_ptr<Foo>&& foo) : m_foo(std::move(foo))
    {
    }

    int B()
    {
        return m_foo->F();
    }

  private:
    std::unique_ptr<Foo> m_foo;
};

class MockFoo : public Foo
{
  public:
    MOCK_METHOD0(F, int());
};

class BarTest : public Test
{
};

TEST_F(BarTest, Test1)
{
    auto mock_foo = std::make_unique<MockFoo>();
    ON_CALL(*mock_foo, F()).WillByDefault(Return(1));

    Bar bar(std::move(mock_foo));

    auto val = bar.B();

    EXPECT_THAT(val, 1);
}

测试运行良好,但出现以下错误:

The test runs well but I got the following error:

... test.cpp:293:错误:应删除此模拟对象(用于测试BarTest.Test1),但绝对不要删除。它的地址是@ 0x1c7c590。
错误:1个泄漏的模拟对象在程序出口处发现。

我认为Google Test认为我没有销毁 mock_foo ,但是它没有看到不必将其删除,因为它已被移动。测试是安全的,因为对象本身是相同的,只是所有权已更改(这是我的意图)。

I think Google Test thinks that I have not destroyed mock_foo but it does not see that it does not have to be deleted here because it has been moved. The test is safe because the object itself is the same, just the ownership has changed (which is my intention).

我的假设正确吗?如果是,我如何抑制此错误消息?不,内存泄漏在哪里?

Is my assumption correct? If yes, how can I suppress this error message? I no, where is the memory leak?

推荐答案

问题是 Foo 没有虚拟析构函数。因此, std :: unique_ptr< Foo> 不会调用派生类的析构函数,而只是调用 Foo 的析构函数。

The problem is that Foo does not have a virtual destructor. std::unique_ptr<Foo> thus won't be calling the derived class's destructor, just Foo's destructor.

class Foo
{
  public:
    virtual ~Foo() = default;
    virtual int F() = 0;
};

请参见何时使用虚拟析构函数?如果基类 Foo 具有虚函数,则它应该具有虚拟析构函数或非公共析构函数。

See When to use virtual destructors? If a base class Foo has virtual functions, it should either have a virtual destructor or a non-public destructor.

这篇关于为什么Google Test / Mock显示std :: unique_ptr泄漏的模拟对象错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆