Is not calling delete on a dynamically allocated object always a memory leak?(对动态分配的对象调用 delete 是否总是内存泄漏?)
问题描述
从讨论开始这里,我想知道以下代码是否存在内存泄漏:>
From the discussion started here, I'd like to know whether the following code has a memory leak:
int main()
{
new int();
//or
int* x = new int();
return 0;
}
我知道内存已被操作系统回收,但这是否是泄漏?我相信是的.
I know the memory is reclaimed by the OS, but is it a leak anyway? I believe it is.
内存泄漏的定义是什么?我只能在标准中找到一个参考,而且不是很有帮助.
What defines a memory leak? I could only find one reference in the standard, and it wasn't very helpful.
我不想开始辩论——我认为……"不是我想要的那种答案.我最感兴趣的是来源 - 什么 C++ 书籍或网站或任何关于它的内容.
推荐答案
第二种情况不是内存泄漏.
这不是泄漏,因为您仍然有一个指向分配的内存的指针.
为了定义内存泄漏,我想坚持大多数内存分析工具(如 valgrind)使用的定义:
Second case is not a memory leak.
It is not a leak because you still have an pointer to the memory that was allocated.
To define a memory leak I would like to stick to definition which most of memory analysis tools like valgrind use:
内存已分配,随后无法释放,因为程序不再有任何指向已分配内存块的指针.
Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block.
这篇关于对动态分配的对象调用 delete 是否总是内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对动态分配的对象调用 delete 是否总是内存泄漏?
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
