c++ - unique_ptr C++ 中的 release()

标签 c++ pointers memory-leaks unique-ptr

这几天我一直在使用 unique_ptr,我对 unique_ptr 的释放方法有疑问。我知道 release 返回 “指向托管对象的指针,如果没有托管对象,则返回 nullptr

假设我们有三个 unique_ptr 变量:

unique_ptr< Node > left(Node);
unique_ptr< Node > right(Node);
unique_ptr< Node > middle(Node);

现在我想更改其中的指针:

middle.release();
right.release();
left.release();

middle.reset(right.get());
right.reset(left.get());
left.reset(middle.get());

这会导致内存泄漏吗?是存储 release() 返回的值然后使用它们更好,还是这样更好?

最佳答案

根据 cppreference.com release() 执行以下操作:

Releases the ownership of the managed object if any. get() returns nullptr after the call.

因此,一旦您释放了所有对象,您就失去了指针!由于它们由 unique_ptr-s 拥有,它们现在处于野外状态!

相反,小心地使用交换来实现相同的目标:

right.swap(middle); // middle = right, right = middle
right.swap(left); // left = right = (old) middle, right = left

关于c++ - unique_ptr C++ 中的 release(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46872819/

相关文章:

c - 格式化代码以访问结构类型的数组索引

c - 关于c编程的内存泄漏问题

c++ - decltype 类型表达式

c++ - Windows/C++ : how to use a COM dll which is not registered

C++11 STL 独有的函数,但反过来

c++ - 访问由 std::find() 找到的项目

c - 返回指向局部变量的指针是UB吗?

c# - 在 C# 中调用此 C 函数的正确语法是什么?该函数使用指针和数组

c - 结构和链表内存分配valgrind错误

python - Keras/Tensorflow疑似内存泄漏