unique_ptr简单实现
时间: 2023-07-12 12:39:29 浏览: 52
下面是一个比较简单的 `unique_ptr` 实现,仅供参考:
```c++
template<typename T>
class unique_ptr {
public:
explicit unique_ptr(T* ptr = nullptr) : ptr_(ptr) {}
~unique_ptr() { delete ptr_; }
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
unique_ptr(unique_ptr&& other) : ptr_(other.ptr_) {
other.ptr_ = nullptr;
}
unique_ptr& operator=(unique_ptr&& other) {
if (this != &other) {
delete ptr_;
ptr_ = other.ptr_;
other.ptr_ = nullptr;
}
return *this;
}
T* operator->() const { return ptr_; }
T& operator*() const { return *ptr_; }
T* get() const { return ptr_; }
private:
T* ptr_;
};
```
这个 `unique_ptr` 类模板实现了动态分配内存的功能,它会在离开作用域时自动释放内存。在这个实现中,我们定义了一个指针成员变量 `ptr_`,用于保存动态分配的内存地址。在默认构造函数中,我们将 `ptr_` 初始化为 `nullptr`。在析构函数中,我们通过 `delete` 操作符释放 `ptr_` 所指向的内存。注意,在拷贝构造函数和赋值操作符中,我们使用 `delete` 关键字将其禁止,确保 `unique_ptr` 不会被拷贝或赋值。在移动构造函数和移动赋值操作符中,我们将 `ptr_` 的值从另一个 `unique_ptr` 对象中移动过来,并将另一个对象的指针成员变量设置为 `nullptr`,避免出现野指针。在 `operator->`、`operator*` 和 `get` 成员函数中,我们分别返回指向内存的指针、操作内存和获取指针本身。