c++实现一个unique_ptr
时间: 2023-09-10 14:10:54 浏览: 53
unique_ptr是一种智能指针,它提供了一种简单的方式来管理动态分配的资源。它的主要特点是:当unique_ptr被销毁时,它所管理的资源也会被自动释放,从而避免了内存泄漏。
以下是一个简单的unique_ptr实现:
```c++
template <typename T>
class unique_ptr {
public:
unique_ptr() : ptr_(nullptr) {}
explicit unique_ptr(T* ptr) : ptr_(ptr) {}
unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;
~unique_ptr() {
delete ptr_;
}
T* operator->() const {
return ptr_;
}
T& operator*() const {
return *ptr_;
}
T* get() const {
return ptr_;
}
void reset(T* ptr = nullptr) {
delete ptr_;
ptr_ = ptr;
}
private:
T* ptr_;
};
```
使用示例:
```c++
unique_ptr<int> p(new int(10));
cout << *p << endl;
p.reset(new int(20));
cout << *p << endl;
```
这个实现中,我们使用了模板类,使得unique_ptr可以管理各种类型的资源。在构造函数中,我们通过一个指针来初始化unique_ptr对象,这个指针所指向的资源就成了unique_ptr所管理的资源。我们重载了成员访问运算符->和解引用运算符*,使unique_ptr可以像指针一样访问所管理的资源。get()函数返回unique_ptr所管理的指针。reset()函数可以用来重置unique_ptr对象,它会先释放原来的资源,然后再接管新的资源。
需要注意的是,在这个实现中,我们禁用了复制构造函数和赋值运算符,这是为了防止unique_ptr对象被复制,从而导致同一份资源被多个unique_ptr对象管理的情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)