Why is GoogleMock leaking my shared_ptr?

倖福魔咒の 提交于 2019-11-29 01:03:35

This is a result of holding p as a shared_ptr, using InSequence and the order in which you have declared your expectations.

When you call

    EXPECT_CALL(*c, myMethod(Eq(p)));

you increase the use_count of p. In order for the leak detection to pass, p must be destroyed at (or before) the end of TEST.

The problem here is that internally, gmock maintains a record of the required mock call sequence by holding a pointer to the preceding expectation. So when you call EXPECT_CALL(*p, myMethod());, it gets a copy of the pointer to the previous expectation.

This then has the effect of blocking the call to p's destructor when TEST ends.

In order to work around this, I think your best bet is to call

    EXPECT_TRUE(Mock::VerifyAndClearExpectations(p.get()));

just before you exit TEST. This clears the expectations on p, including critically its prerequisite expectation, which in turn allows the destructor of p to be invoked correctly.

Alternatively, if the order of the mock calls is unimportant, simply removing InSequence dummy; will also allow p's destructor to execute.


As an aside, your code has a couple of issues;

  • Your base structs should have virtual destructors
  • MyClass::myMethod should be virtual in order to allow gmock's function to override it
  • p->myMethod(p); should be p->myMethod();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!