example5_custom_memory_management.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cxxabi.h>
#include <new>

void* operator new(std::size_t size) {
    std::cout << "Custom global new called, size: " << size << std::endl;
    return std::malloc(size);
}

void operator delete(void* ptr) noexcept {
    std::cout << "Custom global delete called" << 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();
        throw std::runtime_error("Test exception");
        delete obj;  // This won't be called
    } catch (...) {
        std::cout << "Exception caught" << std::endl;
    }

    // Force cleanup of any undeleted objects
    // Most C++ compilers can clean up automatically. The function is not portable. 
    // abi::__cxa_finalize(nullptr);

    return 0;
}
Back to cxxabi.h