【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;
    }
}
相关推荐
uyeonashi2 分钟前
【QT系统相关】QT网络
开发语言·网络·c++·qt
程序猿小D1 小时前
第27节 Node.js Buffer
linux·开发语言·vscode·node.js·c#·编辑器·vim
武昌库里写JAVA1 小时前
【微服务】134:SpringCloud
java·开发语言·spring boot·学习·课程设计
yaoxin5211232 小时前
105. Java 继承 - 静态方法的隐藏
java·开发语言·jvm
我命由我123452 小时前
嵌入式 STM32 开发问题:烧录 STM32CubeMX 创建的 Keil 程序没有反应
c语言·开发语言·c++·stm32·单片机·嵌入式硬件·嵌入式
筏.k2 小时前
C++: 类 Class 的基础用法
android·java·c++
C++ 老炮儿的技术栈2 小时前
手动实现strcpy
c语言·开发语言·c++·算法·visual studio
一条叫做nemo的鱼2 小时前
从汇编的角度揭开C++ this指针的神秘面纱(下)
java·汇编·c++·函数调用·参数传递
Joomla中文网3 小时前
joomla5去掉后台PHP版本警告信息
开发语言·php
大磕学家ZYX3 小时前
使用Nodejs尝试小程序后端服务编写:简单的待办事项管理demo
开发语言·javascript·小程序·node.js