【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;
    }
}
相关推荐
阿巴~阿巴~13 分钟前
二分 —— 基本算法刷题路程
数据结构·c++·算法
徽京人28 分钟前
第八届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组 购物单
c++·职场和发展·蓝桥杯
半桔42 分钟前
哈希表(开散列)的实现
数据结构·c++·面试·散列表·哈希
兴达易控1 小时前
解锁工业通信:Profibus DP到ModbusTCP网关指南!
开发语言·网络·php
Do vis.5761 小时前
set map 代理模式思维导图
c++
阿巴~阿巴~1 小时前
蓝桥杯 C/C++ 组历届真题合集速刷(二)
c语言·c++·算法·蓝桥杯
初见_Dream1 小时前
Android 文件选择器
android·java·开发语言
dot to one1 小时前
深入理解C++面向对象特性之一 多态
c语言·开发语言·c++·visual studio
熊熊饲养员2 小时前
【简单理解什么是简单工厂、工厂方法与抽象工厂模式】
java·开发语言·抽象工厂模式
钢板兽2 小时前
Java常见的23种设计模式
java·开发语言·设计模式