C++内存管理——unique_ptr

C++内存管理——unique_ptr

1. 概述

本想将unique_ptr, shared_ptr和weak_ptr写在同一篇文章中,无奈越(废)写(话)越(连)长(篇),本着不给自己和读者太大压力的原则,最终决定分为三篇去描述它们(不是恶意凑文章数哦)。
本篇文章主要描述了unique_ptr,在此之前先给出了auto_ptr的介绍,废话不说,直入正题。

2. auto_ptr

auto_ptr是在C++ 98中引入的,在C++ 17中被移除掉。它的引入是为了管理动态分配的内存,它的移除是因为本身有严重的缺陷,并且已经有了很好的替代者(unique_ptr)。
auto_ptr采用”Copy”语义,期望实现”Move”语义,有诸多的问题。标准库中的auto_ptr和《Move语义和Smart Pointers先导(以一个例子说明)》中的AutoPtr2十分类似,此处再次给出代码并分析它的问题。

template<typename T>
struct AutoPtr2
{
    AutoPtr2(T* ptr = nullptr)
        : ptr(ptr)
    {
    }

    ~AutoPtr2()
    {
        if(this->ptr != nullptr)
        {
            delete this->ptr;
            this->ptr = nullptr;
        }
    }

    AutoPtr2(AutoPtr2& ptr2) // not const
    {
        this->ptr = ptr2.ptr;
        ptr2.ptr = nullptr;
    }

    AutoPtr2& operator=(AutoPtr2& ptr2) // not const
    {
        if(this == &ptr2)
        {
            return *this;
        }

        delete this->ptr;
        this->ptr = ptr2.ptr;
        ptr2.ptr = nullptr;
        return *this;
    }

    T& operator*() const
    {
        return *this->ptr;
    }

    T* operator->() const
    {
        return this->ptr;
    }

    bool isNull() const
    {
        return this->ptr == nullptr;
    }

private:
    T* ptr;
};
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » C++内存管理——unique_ptr