1. 程式人生 > >自定義內存管理(五十七)

自定義內存管理(五十七)

new 操作符重載 delete 操作符重載

一個筆試題:編寫能統計對象中某個成員變量的訪問次數的程序。我們在類中定義一個私有成員變量,在構造函數中初始化為 0,在進行讀寫操作時都 ++,那麽就達到我們的目的了,下面我們看看程序是怎樣寫的

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int m_Value;
    int m_count;
public:
    Test(int value = 0)
    {
        m_Value = value;
        m_count = 0;
    }
    
    int getValue()
    {
        m_count++;
        
        return m_Value;
    }
    
    int setValue(int value)
    {
        m_count++;
        
        m_Value = value;
    }
    
    int getCount()
    {
        return m_count;
    }
    
    ~Test()
    {
        
    }
};

int main()
{
    Test t;
    
    t.setValue(100);
    
    cout << "t.m_value = " << t.getValue() << endl;
    cout << "t.m_count = " << t.getCount() << endl;
    
    Test ct(200);
    
    cout << "ct.m_value = " << ct.getValue() << endl;
    cout << "ct.m_count = " << ct.getCount() << endl;
    
    return 0;
}

我們來編譯看看結果

技術分享圖片

我們看到已經正確實現功能了哈,類對象也有可能是 const 的,我們來試試 const 類型的呢技術分享圖片

const 對象只能調用 const 成員函數,我們將 getCount 和 getValue 改為 const 成員函數。

技術分享圖片

我們看到又說 m_count 是在 const 成員函數中不能被改變。那麽問題來了,怎樣才能改變 const 成員函數中的限制呢?很幸運,在 C++ 中有一個關鍵字 mutable。mutable 是為了突破 const 函數的限制而設計的,mutable 成員變量將永遠處於可改變的狀態,它在實際的項目開發中被嚴禁濫用。我們先來試試,在 m_count 定義前加上 mutable

技術分享圖片

我們看到編譯通過,並且成功運行。我們再來看看 mutable 關鍵字有什麽特性,mutable 成員變量破壞了只讀對象的內部狀態,const 成員函數保證只讀對象的狀態不變性,mutable 成員變量的出現無法保證狀態不變性。我們再次進行改寫,程序如下

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int m_Value;
    int * const m_pCount;
public:
    Test(int value = 0) : m_pCount(new int(0))
    {
        m_Value = value;
    }
    
    int getValue() const
    {
        *m_pCount = *m_pCount + 1;
        
        return m_Value;
    }
    
    int setValue(int value)
    {
        *m_pCount = *m_pCount + 1;
        
        m_Value = value;
    }
    
    int getCount() const
    {
        return *m_pCount;
    }
    
    ~Test()
    {
        delete m_pCount; 
    }
};

int main()
{
    Test t;
    
    t.setValue(100);
    
    cout << "t.m_value = " << t.getValue() << endl;
    cout << "t.m_count = " << t.getCount() << endl;
    
    const Test ct(200);
    
    cout << "ct.m_value = " << ct.getValue() << endl;
    cout << "ct.m_count = " << ct.getCount() << endl;
    
    return 0;
}

我們定義一個 int* const 類型的指針,然後在構造函數中進行初始化,再利用它進行 ++操作。我們看看編譯結果

技術分享圖片

已經正確實現了哈。下面又是一個很有意思的面試題:new 關鍵字創建出來的對象位於什麽地方?我們大多數人的第一反應是肯定是堆嘛,new 出來的對象肯定在堆上嘛。其實不一定哦。new/delete 的本質是 C++ 預定義的操作符,C++ 對這兩個操作符做了嚴格的行為定義。new:1.獲取足夠大的內存空間(默認為堆空間);2、在獲取的空間中調用構造函數創建對象。delete:1、調用析構函數銷毀對象;2、歸還對象所占用的空間(默認為堆空間)。那麽在 C++ 中是能夠重載 new/delete 操作符的,全局重載(不推薦)和局部重載(針對具體類型進行重載)。重載 new/delete 的意義在於改變動態對象創建時的內存分配方式

下來我們就來利用 new/delete 的重載在靜態存儲區中創建動態對象。

#include <iostream>
#include <string>

using namespace std;

class Test
{
    static const unsigned int COUNT = 4;
    static char c_buffer[];
    static char c_map[];
public:
    void* operator new (unsigned int size)
    {
        void* ret = NULL;
        
        for(int i=0; i<COUNT; i++)
        {
            if( !c_map[i] )
            {
                c_map[i] = 1;
                
                ret = c_buffer + i * sizeof(Test);
                
                cout << "succeed to allocate memory: " << ret << endl;
                
                break;
            }
        }
        
        return ret;
    }
    
    void operator delete (void* p)
    {
        if( p != NULL )
        {
            char* mem = reinterpret_cast<char*>(p);
            int index = (mem - c_buffer) / sizeof(Test);
            int flag = (mem - c_buffer) % sizeof(Test);
            
            if( (flag == 0) && (0 <= index) && (index < COUNT) )
            {
                c_map[index] = 0;
                
                cout << "succeed to free memory: " << c_map[index] << endl;
            }
        }
    }
};

char Test::c_buffer[sizeof(Test) * Test::COUNT];
char Test::c_map[Test::COUNT] = {0};

int main()
{
    cout << "==== Test Single Object ====" << endl;
    
    Test* pt = new Test;
    
    delete pt;
    
    cout << "==== Test Object Array ====" << endl;
    
    Test* pa[5] = {0};
    
    for(int i=0; i<5; i++)
    {
        pa[i] = new Test;
        
        cout << "pa[" << i << "] = " <<pa[i] << endl; 
    }
    
    for(int i=0; i<5; i++)
    {
        cout << "delet " << pa[i] << endl;
        
        delete pa[i];
    }
    
    return 0;
}

我們在全局數據區定義了 4 個數據類型大小的空間,所以只能申請 4 個數據類型大小的空間。在 main 函數中申請了 5 個數據類型,因此編譯器只會分配 4 ,最後一個肯定分配不成功。註意:這都是在全局數據區,而不是在堆上。我們來看看編譯結果

技術分享圖片

我們看到的確是只分配了 4 個 int 類型大小的空間,最後一個為 0,沒分配成功。我們已經利用重載 new/delete 操作符,將 new 出來的對象位於全局數據區了,所以 new 出來的對象不一定是只在堆空間中,只是默認在堆空間中。

下來我們再來看一個面試題:如何在指定的地址上創建 C++ 對象?解決方案:a> 在類中重載 new/delete 操作符;b> 在 new 的操作符重載函數中返回指定的地址;c> 在 delete 操作符重載中標記對應的地址可用。下來我們來看看程序怎麽寫

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Test
{
    static unsigned int c_count;
    static char* c_buffer;
    static char* c_map;
public:
    static bool SetMemorySource(char* memory, unsigned int size)
    {
        bool ret = false;
        
        c_count = size / sizeof(Test);
        
        ret = (c_count && (c_map = reinterpret_cast<char*>(calloc(c_count, sizeof(char)))));
        
        if( ret )
        {
            c_buffer = memory;
        }
        else
        {
            free(c_map);
            
            c_map = NULL;
            c_buffer = NULL;
            c_count = 0;
        }
        
        return ret;
    }
    
    void* operator new (unsigned int size)
    {
        void* ret = NULL;
        
        if( c_count > 0 )
        {
            for(int i=0; i<c_count; i++)
            {
                if( !c_map[i] )
                {
                    c_map[i] = 1;
                    
                    ret = c_buffer + i * sizeof(Test);
                    
                    cout << "succeed to allocate memory: " << ret << endl;
                    
                    break;
                }
            }
        }
        else
        {
            ret = malloc(size);
        }
        
        return ret;
    }
    
    void operator delete (void* p)
    {
        if( p != NULL )
        {
            if( c_count > 0 )
            {
                char* mem = reinterpret_cast<char*>(p);
                int index = (mem - c_buffer) / sizeof(Test);
                int flag = (mem - c_buffer) % sizeof(Test);
                
                if( (flag == 0) && (0 <= index) && (index < c_count) )
                {
                    c_map[index] = 0;
                    
                    cout << "succeed to free memory: " << c_map[index] << endl;
                }
            }
            else
            {
                free(p);
            }
        }
    }
};

unsigned int Test::c_count = 0;
char* Test::c_buffer = NULL;
char* Test::c_map = NULL;

int main()
{
    char buffer[12] = {0};
    
    Test::SetMemorySource(buffer, sizeof(buffer));
    
    cout << "==== Test Single Object ====" << endl;
    
    Test* pt = new Test;
    
    delete pt;
    
    cout << "==== Test Object Array ====" << endl;
    
    Test* pa[5] = {0};
    
    for(int i=0; i<5; i++)
    {
        pa[i] = new Test;
        
        cout << "pa[" << i << "] = " <<pa[i] << endl; 
    }
    
    for(int i=0; i<5; i++)
    {
        cout << "delet " << pa[i] << endl;
        
        delete pa[i];
    }
    
    return 0;
}

我們在全局數據區自定義數組 buffer,然後再在 buffer 裏進行操作。看看編譯結果

技術分享圖片

我們看到已經正確實現了。還有一個:new[] / delete[] 和 new / delete 一樣嗎?它們是完全不同的。動態對象數組創建通過 new[] 完成,動態對象數組的銷毀通過 delete[] 完成。而 new[] / delete[] 能夠被重載,進而會改變內存管理方式。通過 new[] 操作,實際返回的內存空間可能比期望的要多。因為對象數組占用的內存中需要保存數組信息,數組信息用於確定構造函數和析構函數的調用次數。

下來我們還是通過示例代碼來進行分析

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Test
{
    int m_Value;
public:
    Test()
    {
        m_Value = 0;
    }
    
    ~Test()
    {
    }
    
    void* operator new (unsigned int size)
    {
        cout << "operator new: " << size << endl;
        
        return malloc(size);
    }
    
    void operator delete (void* p)
    {
        cout << "operator delete: " << p << endl;
        
        free(p);
    }
    
    void* operator new[] (unsigned int size)
    {
        cout << "operator new[]: " << size << endl;
        
        return malloc(size);
    }
    
    void operator delete[] (void* p)
    {
        cout << "operator delete[]: " << p << endl;
        
        free(p);
    }
};

int main()
{
    Test* pt = NULL;
    
    pt = new Test;
    
    delete pt;
    
    pt = new Test[5];
    
    delete[] pt;
    
    return 0;
}

按照我們之前的想法是 new[5] 肯定是 20了,但是我們今天剛講了它是需要額外的存儲空間來存放用於管理數組信息的空間的,因此申請出來的肯定會比 20 大。我們來看看編譯結果

技術分享圖片

我們看到申請數組申請出來的是 24 個字節的空間。通過對一些經典面試題的學習,總結如下:1、new/delete 的本質為操作符;2、可以通過全局函數重載 new/delete(不推薦),也可以針對具體的類進程重載 new/delete;3、new[] / delete[] 與 new/delete 完全不同;4、new[] / delete[] 也是可以被重載的操作符,new[] 返回的內存空間可能比期望的要多。


歡迎大家一起來學習 C++ 語言,可以加我QQ:243343083

自定義內存管理(五十七)