
























// 全局重载示例 void* operator new(std::size_t size) { std::cout << "Custom operator new called, size: " << size << std::endl; return malloc(size); // 调用 malloc 分配内存 } // 类专属重载示例 class MyClass { public: static void* operator new(std::size_t size) { std::cout << "MyClass::operator new called" << std::endl; return ::operator new(size); // 调用全局 operator new } };
3223
#include <iostream> #include <new> // for std::bad_alloc class MyClass { public: MyClass() { std::cout << "Constructor called" << std::endl; } ~MyClass() { std::cout << "Destructor called" << std::endl; } // 重载全局 operator new static void* operator new(std::size_t size) { std::cout << "Global operator new called, size: " << size << std::endl; void* ptr = malloc(size); if (!ptr) throw std::bad_alloc(); return ptr; } // 重载全局 operator delete static void operator delete(void* ptr) noexcept { std::cout << "Global operator delete called" << std::endl; free(ptr); } }; int main() { // 使用 new 操作符(调用 operator new 和构造函数) MyClass* obj = new MyClass(); // 使用定位分配(在栈内存上构造对象) char buffer[sizeof(MyClass)]; MyClass* placementObj = new (buffer) MyClass(); // 释放资源 delete obj; // 调用析构函数和 operator delete placementObj->~MyClass(); // 手动调用析构函数(定位分配需手动析构) return 0; }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。