如何修复 C++ 项目中的内存泄漏?

How to fix this memory leak in C++ project?

我有非常简单的代码片段:

struct simple_string
{
    simple_string(size_t size, char ch)
    : buffer_(new Buffer(std::basic_string<char, std::char_traits<char>>(size, ch).c_str(), size)) //first memory leak
    {
    }

    ~simple_string()
    {
        buffer_->release();
        delete buffer_;
    }

    struct Buffer
    {
        explicit Buffer(const char* str, size_t size)
        : str_(new char[size + 1]), //second memory leak
        count_(1)
        {
            std::char_traits<char>::copy(str_, str, size + 1);
        }

        void release()
        {
            if (this != nullptr)
            {
                --count_;

                if (count_ == 0)
                {
                    delete[] str_;
                }
            }
        }

        void acquire()
        {
            ++count_;
        }

        char* str_;
        size_t count_;
    } *buffer_;
};

int main() {
    simple_string a(3, 'a');

    return 0;
}

我不明白,为什么会存在内存泄漏。两个原始指针都在程序生命周期结束时被删除。也许我不应该在构造函数的初始化列表中创建指针?

Are there any issues with allocating memory within constructor initialization lists?

尝试切换到真正的智能指针,也许您收到的内存泄漏是警告而不是当时的实际泄漏?

我使用 g++ 4.8.2 + valgrind 3.10 没有出现内存泄漏。

我在 VS 2015 EE 中使用 CRTDBG_MAP_ALLOC 检测到它,但这是误报。

在删除指针后将str_buffer_设置为nullptr,然后显式调用析构函数:a.~simple_string();,它会调用两次析构函数,第二次实际上没有做任何事情,但它会显示没有内存泄漏,因为在输出内存泄漏结果之前第一次调用析构函数。

编辑: 可以通过在函数中创建 simple_string 对象而不是 [=15] 来解决这种误报内存泄漏(至少在 VS2015 EE 中) =]:

void foo()
{
    simple_string a(3, 'a');
}

int main() 
{
    foo();

    return 0;
}