unique_ptr
时间: 2023-08-14 13:07:13 浏览: 57
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 实现,它包含了构造函