这可能是内存泄漏吗?
Could this be a memory leak?
使用新的 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
这比原始指针略贵,但不太容易发生内存泄漏。智能指针位于<内存>标头中。内存>
相关文章:
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 析构函数 C++ 使泄漏内存
- 构造函数对象赋值是否泄漏内存
- corba :: orb_init泄漏内存
- Gmock泄漏内存
- 如何在不泄漏内存的情况下删除链接列表
- Visual C ODBC关闭记录集泄漏内存
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- OpenGL正在泄漏内存.哪个对象未释放
- 可以std ::退出泄漏内存
- uiautomation findall泄漏内存
- 为什么在此OpenCL代码中泄漏内存,为什么要泄漏内存
- pthread在完成后会泄漏内存
- win32 标准::线程泄漏内存
- 返回指向同一变量的指针是否会泄漏内存
- 使用clectType(new any_type())可能会泄漏内存泄漏
- Windows开发:如何确定我的应用程序是否正在泄漏内存
- WinHttp打开泄漏内存