对动态分配的对象调用 delete 是否总是内存泄漏?

2023-09-26C/C++开发问题
1

本文介绍了对动态分配的对象调用 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 是否总是内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6