如何自定義C++中new()的行為

c++
小樊
83
2024-09-06 07:18:20

在 C++ 中,您可以通過(guò)重載 operator newoperator delete 函數(shù)來(lái)自定義 new 操作符的行為。這些操作符用于分配和釋放內(nèi)存。

下面是一個(gè)簡(jiǎn)單的示例,展示了如何重載 operator newoperator delete 以跟蹤內(nèi)存分配:

#include<iostream>
#include <cstdlib> // for std::size_t

// 自定義 operator new
void* operator new(std::size_t size) {
    std::cout << "Custom new: allocating "<< size << " bytes"<< std::endl;
    void* ptr = std::malloc(size);
    if (ptr == nullptr) {
        throw std::bad_alloc();
    }
    return ptr;
}

// 自定義 operator delete
void operator delete(void* ptr) noexcept {
    std::cout << "Custom delete: freeing memory at "<< ptr<< std::endl;
    std::free(ptr);
}

class MyClass {
public:
    MyClass() {
        std::cout << "MyClass constructor"<< std::endl;
    }

    ~MyClass() {
        std::cout << "MyClass destructor"<< std::endl;
    }
};

int main() {
    try {
        MyClass* obj = new MyClass();
        delete obj;
    } catch (const std::bad_alloc& e) {
        std::cerr << "Allocation failed: " << e.what()<< std::endl;
    }

    return 0;
}

在這個(gè)示例中,我們重載了全局的 operator newoperator delete 函數(shù)。當(dāng)使用 new 關(guān)鍵字創(chuàng)建對(duì)象時(shí),將調(diào)用自定義的 operator new 函數(shù)。同樣,當(dāng)使用 delete 關(guān)鍵字刪除對(duì)象時(shí),將調(diào)用自定義的 operator delete 函數(shù)。

請(qǐng)注意,這只是一個(gè)簡(jiǎn)單的示例,實(shí)際上您可能需要處理更復(fù)雜的情況,例如重載 operator new[]operator delete[] 以支持?jǐn)?shù)組分配,或者為特定類型的對(duì)象提供不同的內(nèi)存管理策略。

0