c++ - 当 std::string 大小 >= 16 时内存泄漏

标签 c++

我收到有关此不完整测试用例的内存泄漏报告。如果我改为传递“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/

相关文章:

c++ - OpenCV c++ HoughLines 转换不起作用

c++ - 在不知道类型的情况下将基类的指针转换为派生模板类

c++ - 使用 Awesomium 在 DirectX 窗口上渲染(半透明和圆形元素)

c++ - 如何强制 Visual Studio 使用 wmain 而不是 main

c++ - CString 到 const byte* 的 Unicode 项目?

c++ - 字符串/wchar 内容不一致取决于代码的位置?

c++ - 如何优化自定义日期结构的比较功能?

c++ - 为什么 CMFCToolbar 中的自定义按钮在大图标上很难看

c++ - 你如何构造一个带有嵌入空值的 std::string?

c++ - EOF 上的 std::ws 行为