c++ - std::vector 中的 clear() 是否会产生内存泄漏?

标签 c++ c++11 memory-leaks stdvector

我的问题几乎是这个问题的延伸:Is std::vector memory freed upon a clear?

这里有人解释说,为 std::vector 的元素分配的内存在调用 clear() 后不会释放。但是,操作系统是否可以免费使用此内存以允许其他程序使用它,或者我的程序是否可以在其他任何地方使用它?

如果不是(如果内存继续只分配给这个 vector 并且我不能再访问它)是不是像我们使用指针的内存泄漏?然后像这样单独使用 clear() 是完全不安全的,对吧?

如果有人能在这方面澄清我的话,我会很高兴。谢谢。

最佳答案

Does clear() in std::vector generates a memory leak?

没有。

But will this memory be free for the OS to allow other programs to use it or will it be available for my program to use it anywhere else?

操作系统可以将内存交换到磁盘,以允许其他程序使用物理内存。

if the memory continues to be allocated only for this vector and I can't access it anymore

您可以通过向 vector 中添加新对象来重用内存。或者通过破坏载体来释放它。析构函数绝对保证释放内存。

isn't it a memory leak like the ones we have with pointers?

没有。当指向内存的指针丢失时,就会发生内存泄漏。但在这种情况下,vector 会安全地跟踪指针,并在它被销毁时释放它。

Then clear() when used alone like this would be totally unsafe right?

clear 本身并不是不安全的,但它会释放内存的假设可能是不安全的。

关于c++ - std::vector 中的 clear() 是否会产生内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41595134/

相关文章:

.net - 将委托(delegate)传递给静态类会导致泄漏吗?

ios - 使用 ABRecord 和 ARC 的潜在泄漏

c++ - 在 msvc 和 gcc 上使用 vsnprintf 时的不同行为

C++ 析构函数约定

c++ - 为什么 Visual Studio 2010 调试器看不到静态 const 类成员?

c++ - 重载 [] 和 , c++11

c++ - 可能的内存泄漏?

c++ - 使用 C++ chrono 以纳秒为单位打印当前系统时间

c++ - 在 C++11 中,引用在运行时明显发生变化

python - pyocr 与 tesseract 内存不足