C++ 中的 new operator, operator new,placement new

new operator
 string *sp = new string("hello world");
 delete sp;

這里的new稱之為 new operator(new 運(yùn)算符),它做2件事:

  • 調(diào)用的是標(biāo)準(zhǔn)庫(kù)函數(shù)operator new分配一塊足夠大的,未命名的內(nèi)存空間。
  • 編譯器運(yùn)行相應(yīng)的構(gòu)造函數(shù)在剛才分配的內(nèi)存上構(gòu)造對(duì)象 , 并返回指向該對(duì)象的指針。

這里的delete它做2件事:

  • 調(diào)用該對(duì)象的析構(gòu)函數(shù)
  • 調(diào)用標(biāo)準(zhǔn)庫(kù)函數(shù)operator delete釋放內(nèi)存
operator new, operator delete函數(shù)
/* 這些版本可能拋出異常 new分配失敗,拋出bad_alloc異常 */
void *operator new(size_t);    
void *operator new[](size_t);
void *operator delete(void*);
void *operator delete[](void*);

/* 下面版本承諾不拋出異常 new分配失敗,不拋出異常,返回nullptr指針 */
void *operator new(size_t, nothrow_t &)  noexcept;    
void *operator new[](size_t, nothrow_t &)  noexcept;
void *operator delete(void*, othrow_t &)  noexcept;
void *operator delete[](void*, othrow_t &)  noexcept;

我們可以在全局或者類里面自定義上面的函數(shù),當(dāng)我們將其定義成類的成員函數(shù)時(shí),它是隱式靜態(tài)成員函數(shù)。

/* 編寫operator new(分配內(nèi)存) 和 operator delete(釋放內(nèi)存)簡(jiǎn)單實(shí)現(xiàn)方式 */
void* operator new(size_t size) 
{
    if (void *mem = malloc(size))
        return mem;
    else
        throw bad_alloc();
}

void* operator delete() noexcept
{
    free(mem);
}
placement new

上面的 operator new 只是分配內(nèi)存,而 placement new 不分配內(nèi)存,只負(fù)責(zé)在預(yù)先分配的內(nèi)存上構(gòu)造對(duì)象。

new (place_address) type;
new (place_address) type(initializers);
new (place_address) type[size];
new (place_address) type[size]{ braced initializers list };
  • 例子:
string *sp = static_cast<string*>(::operator new(sizeof(string)));  //operator new 分配內(nèi)存
new (sp) string("hello world");  // placement new 構(gòu)造對(duì)象
    
cout << *sp << endl;
    
sp->~string();    // 主動(dòng)調(diào)用析構(gòu)函數(shù)
::operator delete(sp);  //operator delete 釋放內(nèi)存
set_new_handler

set_new_handler 是一個(gè)"接受一個(gè)不接受參數(shù)也無返回值的函數(shù)"的函數(shù)指針,而這個(gè)函數(shù)就被用來處理bad_alloc異常。( void *operator new(size_t) 或者 void *operator new 分配內(nèi)存失敗 )。

  • 例子
#include <iostream>     
#include <cstdlib>      
#include <new>

void no_memory() 
{
    std::cout << "Failed to allocate memory!\n";
    std::exit (1);
}

int main() 
{
    std::set_new_handler(no_memory);
    std::cout << "Attempting to allocate 2 GiB..." << std::endl;
    char* p = new char [2 * 1024 * 1024 * 1024];
    std::cout << "ok\n";
    delete[] p;
    return 0;
}
應(yīng)用:不用工具,實(shí)現(xiàn)檢測(cè)內(nèi)存泄漏

整體思路:在申請(qǐng)內(nèi)存時(shí)記錄下該內(nèi)存的地址和在代碼中申請(qǐng)內(nèi)存的位置,在內(nèi)存銷毀時(shí)刪除該地址對(duì)應(yīng)的記錄,程序最后統(tǒng)計(jì)下還有哪條記錄沒有被刪除,如果還有沒被刪除的記錄就代表有內(nèi)存泄漏。

  • 重載operator new 函數(shù)

    void *operator new(std::size_t size, const char *file, int line);
    void *operator new[](std::size_t size, const char *file, int line);
    
  • 使用宏定義替換new

    #define new new (__FILE__, __LINE__)        // new operator
    
  • 申請(qǐng)內(nèi)存多申請(qǐng)一段內(nèi)存記錄元信息

    std::mutex new_output_lock;
    std::mutex new_ptr_lock;
    long long total_mem_alloc = 0;
    new_ptr_list_t new_ptr_list;
    
    void *operator new(std::size_t size, const char *file, int line)
    {
        return alloc_mem(size, file, line, false);
    }
    
    void *operator new[](std::size_t size, const char *file, int line)
    {
        return alloc_mem(size, file, line, true);
    }
    
    static void *alloc_mem(std::size_t size, const char *file, int line, bool is_array)
    {
        assert(line >= 0);
    
        std::size_t s = size + ALIGNED_LIST_ITEM_SIZE;
        new_ptr_list_t *ptr = (new_ptr_list_t *)malloc(s);
        if (ptr == nullptr)
        {
            std::unique_lock<std::mutex> lock(new_output_lock);
            printf("Out of memory when allocating %lu bytes\n", (unsigned long)size);
            abort();
        }
        void *usr_ptr = (char *)ptr + ALIGNED_LIST_ITEM_SIZE;
    
        if (line)
        {
            strncpy(ptr->file, file, DEBUG_NEW_FILENAME_LEN - 1);
            ptr->file[DEBUG_NEW_FILENAME_LEN - 1] = '\0';
        }
        else
        {
            ptr->addr = (void *)file;
        }
    
        ptr->line = line;
        ptr->is_array = is_array;
        ptr->size = size;
        ptr->magic = DEBUG_NEW_MAGIC;
    
        // 鏈表操作
        // 插入鏈表中
    
        total_mem_alloc += size;
    
        return usr_ptr;
    }
    
  • 釋放內(nèi)存
    鏈表中找到要對(duì)應(yīng)節(jié)點(diǎn),刪除掉,

    void operator delete(void* ptr) noexcept { 
        free_pointer(ptr, nullptr, false); 
    }
    static void free_pointer(void* usr_ptr, void* addr, bool is_array) {
        if (usr_ptr == nullptr) 
        {
            return;
        }
        new_ptr_list_t* ptr = (new_ptr_list_t*)((char*)usr_ptr - ALIGNED_LIST_ITEM_SIZE);
        {
              // 鏈表移除結(jié)點(diǎn)操作
        }
        free(ptr);
    }
    
  • 如何檢測(cè)是否有內(nèi)存泄漏?
    遍歷鏈表即可,每次new時(shí)候會(huì)把這段內(nèi)存插入鏈表,delete時(shí)候會(huì)把這段內(nèi)存從鏈表中移出,如果程序最后鏈表長(zhǎng)度不為0,即為有內(nèi)存泄漏。

  • 沒有被new宏包裹的地方可以檢測(cè)的到嗎?
    沒有被new宏包裹的地方是會(huì)調(diào)用operator new(std::size_t sz)函數(shù)來申請(qǐng)內(nèi)存的。這里operator new函數(shù)不只可以重載,還可以重新定義它的實(shí)現(xiàn),因?yàn)樗且粋€(gè)weak symbol,有關(guān)strong symbol和weak symbol的知識(shí)點(diǎn)可以看:強(qiáng)弱符號(hào)的問題

    void* operator new(std::size_t size) { 
        return operator new(size, nullptr, 0); 
    }
    

參考資料
1、https://www.zhihu.com/question/29859828/answer/1798470821

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容