unique_ptr release
时间: 2023-11-26 09:03:49 浏览: 31
`unique_ptr` 的 `release()` 方法用于释放指针的所有权,返回指针并将 `unique_ptr` 置为空指针。这意味着,`unique_ptr` 不再拥有指针,指针的生命周期由调用 `release()` 的代码块控制。下面是一个使用 `release()` 方法的例子:
```c++
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> p1(new int(5));
int* p2 = p1.release(); // 释放所有权
std::cout << *p2 << std::endl; // 输出:5
delete p2; // 释放内存
return 0;
}
```
在上面的例子中,我们首先创建了一个 `unique_ptr` 对象 `p1`,它指向一个动态分配的整型变量。然后,我们调用 `release()` 方法释放了 `p1` 对指针的所有权,并将指针赋值给了 `p2`。最后,我们输出了 `p2` 指向的整型变量的值,并手动释放了内存。
相关问题
unique_ptr
unique_ptr 是 C++ 标准库中的一个智能指针类,用于管理动态分配的对象,确保在不再需要时正确释放内存。虽然我无法提供完整的 unique_ptr 源码,但我可以给您一个简单的示例来说明其工作原理。
```cpp
template <typename T>
class unique_ptr {
public:
// 构造函数
explicit unique_ptr(T* ptr = nullptr) : m_ptr(ptr) {}
// 禁用拷贝构造函数和赋值操作符
unique_ptr(const unique_ptr<T>&) = delete;
unique_ptr<T>& operator=(const unique_ptr<T>&) = delete;
// 移动构造函数和移动赋值操作符
unique_ptr(unique_ptr<T>&& other) noexcept : m_ptr(other.release()) {}
unique_ptr<T>& operator=(unique_ptr<T>&& other) noexcept {
if (this != &other) {
reset(other.release());
}
return *this;
}
// 析构函数
~unique_ptr() {
reset();
}
// 获取原始指针
T* get() const {
return m_ptr;
}
// 重载箭头操作符
T* operator->() const {
return m_ptr;
}
// 重载解引用操作符
T& operator*() const {
return *m_ptr;
}
// 重置智能指针
void reset(T* ptr = nullptr) {
if (m_ptr) {
delete m_ptr;
}
m_ptr = ptr;
}
// 释放指针所有权,返回原始指针并将智能指针置空
T* release() {
T* ptr = m_ptr;
m_ptr = nullptr;
return ptr;
}
private:
T* m_ptr;
};
```
上述代码是一个简化的 unique_ptr 实现,它包含了构造函
unique_ptr方法
unique_ptr是C++11中引入的一种智能指针,用于管理动态分配的对象。它的特点是独占式拥有权,即同一时间只能有一个unique_ptr指向一个对象,当unique_ptr被销毁时,它所指向的对象也会被销毁。unique_ptr提供了多种方法来操作指针,包括reset、release、get等方法。同时,unique_ptr还支持移动语义,可以通过std::move将一个unique_ptr的所有权转移给另一个unique_ptr,从而实现资源的转移和管理。在使用unique_ptr时需要注意,不能将一个unique_ptr赋值给另一个unique_ptr,除非使用std::move进行转移。而将一个unique_ptr作为函数参数传递时,可以使用左值引用的方式,保证函数调用后unique_ptr仍然占有指向的资源。