【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;
    }
}
相关推荐
小欣加油几秒前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
王璐WL11 分钟前
【c++】c++第一课:命名空间
数据结构·c++·算法
aramae18 分钟前
C++ -- 模板
开发语言·c++·笔记·其他
胡耀超18 分钟前
4、Python面向对象编程与模块化设计
开发语言·python·ai·大模型·conda·anaconda
索迪迈科技1 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
Zz_waiting.1 小时前
Javaweb - 14.6 - Vue3 数据交互 Axios
开发语言·前端·javascript·vue·axios
萌新小码农‍1 小时前
Java分页 Element—UI
java·开发语言·ui
Tiger_shl2 小时前
【.Net技术栈梳理】03-核心框架与运行时(异常处理)
开发语言·.net
再睡亿分钟!2 小时前
Spring MVC 的常用注解
java·开发语言·spring boot·spring
MChine慕青2 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表