这可能是内存泄漏吗?

Could this be a memory leak?

本文关键字:泄漏 内存      更新时间:2023-10-16

使用新的 then 设置为 null 会导致内存泄漏吗?

我尝试了以下代码,但不知道它是否会导致任何泄漏

#include <iostream>
using namespace std;
int main()
{
   int* x = new int;
   int y = 1;
   x = &y;
   x = nullptr; // has the memory allocated to x gone now?
   x =&y;       // did i recover what was lost?
   delete x;   
   return 0;
}

cout<<*x 按预期给出 1

是的,这是一个泄漏。但是,当您将nullptr分配给x时,泄漏不会发生,而是在它前面的行中发生:

x = &y;

x现在指向 y 的地址,并且不存在对您分配的内存的其他引用new int。如果对该内存没有任何引用,则无法解除分配它。

当您指定为保存它的唯一指针时,指向的对象将丢失。如上所述,x = &y已经失去了你的new int。你以后所做的任何事情都不能把它带回来。这意味着delete调用未定义的行为,并可能导致程序崩溃。

但是,C++中有一种机制可以避免此类内存泄漏:智能指针。

在C++智能指针有两种主要品种 ::std::unique_ptr<T>::std::shared_ptr<T> .他们的工作是保留动态内存中的对象,并确保在对象变为无主状态时将其删除:

::std::unique_ptr<int> x = ::std::make_unique<int>(0);
x = nullptr; // automatically deletes the previously allocated int

这比原始指针略贵,但不太容易发生内存泄漏。智能指针位于<内存>标头中。