【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;
    }
}
相关推荐
Cx330❀4 分钟前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
云间月13149 分钟前
飞算JavaAI智慧文旅场景实践:从景区管理到游客服务的全链路系统搭建
java·开发语言
杜子不疼.27 分钟前
《Python学习之使用标准库:从入门到实战》
开发语言·python·学习
意疏31 分钟前
【C语言篇】srand函数的详细用法解析
c语言·开发语言
艾莉丝努力练剑1 小时前
【C语言16天强化训练】从基础入门到进阶:Day 1
c语言·开发语言·数据结构·学习
颖川守一1 小时前
C++c6-类和对象-封装-设计案例2-点和圆的关系
开发语言·c++
飞剑神1 小时前
qt svg缺失元素, 原因是不支持 rgba
开发语言·qt
charlee441 小时前
将std容器的正向迭代器转换成反向迭代器
c++
arbboter2 小时前
【C++20】新特性探秘:提升现代C++开发效率的利器
c++·c++20·新特性·span·结构化绑定·初始化变量·模板参数推导
zc.ovo2 小时前
图论水题4
c++·算法·图论