【C++】智能指针

独占智能指针的概述

独占智能指针会"拥有"它所指向的对象,某一时刻,只能有一个unique_ptr指向给定的对象,当该指针被销毁时,指向的对象也会随之释放。

手写智能指针

#ifndef UNIQUE_PTR_H
#define UNIQUE_PTR_H
#include <iostream>
#include<memory>

using namespace std;
template <typename T, typename D = default_delete<T>>
class my_unique_ptr
{
    T* pointer;
    D deleter;
public:
    explicit my_unique_ptr(T p) noexcept; // 不可用于转换函数。
    ~my_unique_ptr() noexcept;
    T& operator*() const;  // 重载*操作符。
    T* operator->() const noexcept; // 重载->操作符。
    my_unique_ptr(const my_unique_ptr &) = delete; // 禁用拷贝构造函数
    my_unique_ptr& operator=(const my_unique_ptr &) = delete; // 禁用赋值函数
    my_unique_ptr(my_unique_ptr &&) noexcept; // 右值引用。
    my_unique_ptr& operator=(my_unique_ptr &&) noexcept; // 右值引用

private:
    T *ptr; // 内置的指针。
};
#endif // UNIQUE_PTR_H

template <typename T, typename D >
my_unique_ptr<T,D>::my_unique_ptr(T p) noexcept {}// 不可用于转换函数。

template <typename T, typename D >
my_unique_ptr<T,D>::~my_unique_ptr() noexcept
{
    deleter(pointer);//删除托管的指针
}
template <typename T, typename D >
T& my_unique_ptr<T,D>::operator*() const  // 重载*操作符。
{
    return *pointer;//返回托管指着内的内容
}
template <typename T, typename D >
T* my_unique_ptr<T,D>::operator->() const noexcept// 重载->操作符。
{
    return pointer;//返回原指针的地址
}
// 右值引用。
template <typename T, typename D >
my_unique_ptr<T,D>::my_unique_ptr(my_unique_ptr &&other) noexcept
    :pointer(other.pointer),ptr(other.ptr),
      deleter(std::move(other.deleter))//调用函数时候就直接进程初始化了
{
    this->pointer = other.pointer;
    this->ptr = other.ptr;
}
template <typename T, typename D >
my_unique_ptr<T,D>& my_unique_ptr<T,D>::operator=(my_unique_ptr &&other) noexcept // 右值引用
{
    if(this != other)
    {
        deleter(pointer);
        this->pointer = other.pointer;
        this->ptr = other.ptr;
        deleter = move(other.deleter);
        other.pointer = nullptr;
        other.ptr = nullptr;
    }
}
相关推荐
MSTcheng.3 分钟前
【C语言】指针(5)
c语言·开发语言
╮壞孩子的天4 分钟前
C语言多人聊天室 ---chat(客户端聊天)
c语言·开发语言
IT猿手15 分钟前
2025高维多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
开发语言·人工智能·算法·机器学习·matlab·无人机·cocos2d
呱牛do it19 分钟前
Python Matplotlib图形美化指南
开发语言·python·matplotlib
pianmian122 分钟前
python制图之小提琴图
开发语言·python·信息可视化
水瓶丫头站住23 分钟前
Qt中QRadioButton的使用
开发语言·qt
非 白29 分钟前
【Java】代理模式
java·开发语言·代理模式
知识分享小能手35 分钟前
Html5学习教程,从入门到精通,HTML5 简介语法知识点及案例代码(1)
开发语言·前端·javascript·学习·前端框架·html·html5
muxue17838 分钟前
go:运行第一个go语言程序
开发语言·后端·golang
米饭好好吃.39 分钟前
【Go】Go wire 依赖注入
开发语言·后端·golang