溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

仿函數(shù),()的重載

發(fā)布時(shí)間:2020-07-26 21:18:57 來源:網(wǎng)絡(luò) 閱讀:183 作者:be_better_ 欄目:編程語言

以智能指針為例說明,具體看注釋:

template<class T>
class DFDef
{
public:
    void operator()(T*& p)//()的重載,只需要接受一個(gè)T類型對(duì)象的指針
    {
        if (p)
        {
            delete p;
            p = nullptr;
        }
    }
};

template<class T>
class Free
{
public:
    void operator()(T*& p)
    {
        if (p)
        {
            free(p);
            p = nullptr;
        }
    }
};

class FClose
{
public:
    void operator()(FILE*& p)
    {
        if (p)
        {
            fclose(p);
            p = nullptr;
        }
    }
};

namespace bite
{
    template<class T, class DF = DFDef<T>>//DF是一個(gè)自定義類型模板,默認(rèn)調(diào)用DFDef
    class unique_ptr
    {
    public:
        // RAII
        unique_ptr(T* ptr = nullptr)
            : _ptr(ptr)
        {}

        ~unique_ptr()
        {
            if (_ptr)
            {
                //delete _ptr; // 釋放資源的方式固定死了,只能管理new的資源,不能處理任意類型的資源
                //DF()(_ptr);
                DF df;//創(chuàng)建一個(gè)DF對(duì)象
                df(_ptr);//調(diào)用df中的()重載,傳入指針
                _ptr = nullptr;
            }
        }

        // 具有指針類似行為
        T& operator*()
        {
            return *_ptr;
        }

        T* operator->()
        {
            return _ptr;
        }

        unique_ptr(const unique_ptr<T>&) = delete;  // 1. 釋放new的空間  2.默認(rèn)成員函數(shù) = delete : 告訴編譯器,刪除該默認(rèn)成員函數(shù)
        unique_ptr<T>& operator=(const unique_ptr<T>&) = delete;

    private:
        T* _ptr;
    };
}

#include<malloc.h>
void TestUniquePtr()
{
    //通過模板參數(shù)列表的第二個(gè)參數(shù),選擇在析構(gòu)時(shí)選擇對(duì)應(yīng)的析構(gòu)方法
    bite::unique_ptr<int> up1(new int);
    bite::unique_ptr<int, Free<int>> up2((int*)malloc(sizeof(int)));//傳一個(gè)類進(jìn)去
    bite::unique_ptr<FILE, FClose> up3(fopen("1.txt", "w"));
}

int main()
{
    TestUniquePtr();
    return 0;
}
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI