gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:09:15 24 4
gpt4 key购买 nike

我的问题几乎是这个问题的延伸: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com