我收到有关此不完整测试用例的内存泄漏报告。如果我改为传递“nameNameNameNam”,则不会有泄漏报告。
TEST_F (TestDoesExist, namePassedToCInterface)
{
Accessor accessor(_cInterface, _handle);
accessor.doesExist(std::string("nameNameNameName"));
}
被测代码如下所示:
virtual bool doesExist(const std::string& name)
{
bool result;
_cInterface.exists(_txHandle, name.c_str(), &result);
return result;
}
C接口(interface)的调用模拟如下:
class MockDoesExist
{
public:
MockDoesExist() {
handle=Handle();
name = "";
result = true;
}
static void func(Handle _handle, const char* _name, bool* _result) {
// in values
handle = _handle;
name = _name;
// out values
*_result = result;
}
// in values
static Handle handle;
static std::string name;
// out values
static bool result;
};
Handle MockDoesExist::handle;
std::string MockDoesExist::name;
bool MockDoesExist::result;
我正在使用 VS 2010 Express 进行编译。
我有:
_CrtMemCheckpoint( &memAtStart );
在测试用例执行之前和:
_CrtMemDifference( &memDiff, &memAtStart, &memAtEnd)
之后。
我做错了什么?
最佳答案
没有。 _CrtMemDifference
在测试用例之后调用,但 之前 MockDoesExist
的静态成员被销毁(它们在程序终止之前被销毁)。在您的测试用例中,MockDoesExist::name
被分配给您的长字符串。在 MSVC 的标准库中,有一个针对短字符串的优化,这意味着每个 std::string 都有一个内部 16 字节的字符数组,可以存储较短的字符串。只有对于较长的字符串,它才必须从空闲存储中分配内存。该内存将在字符串的析构函数中释放,在这种情况下,当 MockDoesExist::name
被销毁时,即在调用 _CrtMemDifference
之后。
关于c++ - 当 std::string 大小 >= 16 时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13564969/