在C++中,重载
operator new和
operator delete允许我们为特定类或者全局范围定制内存的分配和释放行为。这通常是为了实现自定义的内存管理策略,比如内存池、内存追踪、对齐控制,或者为了优化性能、诊断内存问题。通过这种方式,你可以完全掌控对象在堆上的生命周期起点和终点,而不仅仅是依赖系统默认的
new和
delete。 解决方案
重载
operator new和
operator delete主要有两种方式:类级别重载和全局重载。
1. 类级别重载
这是最常见且推荐的做法,它只影响特定类的对象分配。当使用
new MyClass时,如果
MyClass重载了
operator new,则会调用该类的版本。
#include <iostream> #include <cstdlib> // For std::malloc, std::free class MyClass { public: int data; MyClass(int d = 0) : data(d) { std::cout << "MyClass constructor called for data: " << data << std::endl; } ~MyClass() { std::cout << "MyClass destructor called for data: " << data << std::endl; } // 重载 operator new static void* operator new(size_t size) { std::cout << "Custom MyClass::operator new called for size: " << size << std::endl; // 实际分配内存,这里我们直接调用全局的 new void* ptr = ::operator new(size); // 必须使用 ::operator new 来避免递归 // 或者使用 std::malloc(size); 但要注意异常处理和对齐 if (!ptr) { throw std::bad_alloc(); } std::cout << "Memory allocated at address: " << ptr << std::endl; return ptr; } // 重载 operator delete static void operator delete(void* ptr) noexcept { std::cout << "Custom MyClass::operator delete called for address: " << ptr << std::endl; // 实际释放内存,这里我们直接调用全局的 delete ::operator delete(ptr); // 必须使用 ::operator delete 来避免递归 // 或者使用 std::free(ptr); std::cout << "Memory deallocated." << std::endl; } // 重载 operator new[] (用于数组) static void* operator new[](size_t size) { std::cout << "Custom MyClass::operator new[] called for size: " << size << std::endl; void* ptr = ::operator new[](size); if (!ptr) { throw std::bad_alloc(); } std::cout << "Array memory allocated at address: " << ptr << std::endl; return ptr; } // 重载 operator delete[] (用于数组) static void operator delete[](void* ptr) noexcept { std::cout << "Custom MyClass::operator delete[] called for address: " << ptr << std::endl; ::operator delete[](ptr); std::cout << "Array memory deallocated." << std::endl; } }; // 示例用法 // int main() { // std::cout << "--- Allocating single MyClass object ---" << std::endl; // MyClass* obj = new MyClass(100); // delete obj; // // std::cout << "\n--- Allocating array of MyClass objects ---" << std::endl; // MyClass* arr = new MyClass[3]; // 注意:这里的构造函数调用不会被自定义的 new[] 打印 // delete[] arr; // // return 0; // }
2. 全局重载
全局重载会影响所有通过
new和
delete进行的内存分配和释放,除非某个类自己重载了它们。这需要非常小心,因为它会改变整个程序的内存管理行为。
#include <iostream> #include <cstdlib> // For std::malloc, std::free // 全局重载 operator new void* operator new(size_t size) { std::cout << "Global operator new called for size: " << size << std::endl; void* ptr = std::malloc(size); // 或者 ::malloc(size); if (!ptr) { throw std::bad_alloc(); } return ptr; } // 全局重载 operator delete void operator delete(void* ptr) noexcept { std::cout << "Global operator delete called for address: " << ptr << std::endl; std::free(ptr); // 或者 ::free(ptr); } // 全局重载 operator new[] void* operator new[](size_t size) { std::cout << "Global operator new[] called for size: " << size << std::endl; void* ptr = std::malloc(size); if (!ptr) { throw std::bad_alloc(); } return ptr; } // 全局重载 operator delete[] void operator delete[](void* ptr) noexcept { std::cout << "Global operator delete[] called for address: " << ptr << std::endl; std::free(ptr); } // 示例用法 // class AnotherClass { // public: // int x; // AnotherClass(int val) : x(val) { std::cout << "AnotherClass constructor: " << x << std::endl; } // ~AnotherClass() { std::cout << "AnotherClass destructor: " << x << std::endl; } // }; // // int main() { // std::cout << "--- Global new/delete test ---" << std::endl; // AnotherClass* ac = new AnotherClass(200); // 会调用全局的 operator new // delete ac; // // int* arr = new int[5]; // 会调用全局的 operator new[] // delete[] arr; // // return 0; // }
请注意,在自定义的
operator new或
operator delete内部,如果你需要实际分配或释放内存,必须调用全局的
::operator new、
::operator delete、
std::malloc或
std::free,而不是再次使用
new或
delete关键字,否则会导致无限递归。 为什么我们要考虑重载
operator new和
operator delete?
我个人觉得,这玩意儿最香的地方,就是能让你对内存有更细粒度的控制,甚至可以说是“夺回”了内存管理的主导权。我们之所以要考虑重载它们,通常是为了解决一些特定的痛点或者追求极致的优化。
一个很典型的场景是内存池(Memory Pooling)。如果你在一个高性能应用中频繁地创建和销毁大量小对象,比如游戏里的粒子、网络请求里的数据包,每次都向操作系统申请和释放内存(也就是调用全局的
new和
delete)开销会很大。操作系统通常会做很多通用性的管理工作,比如寻找合适的空闲块、合并碎片,这些操作相对较慢。而内存池可以预先分配一大块内存,然后自己管理这些小对象的分配和回收。这样一来,分配和释放就变成了简单的指针操作,速度快得多,还能有效减少内存碎片。
再来就是内存调试和追踪。在大型项目中,内存泄漏、越界访问是家常便饭。通过重载
operator new和
operator delete,我们可以在每次内存分配和释放时记录下调用栈、分配大小、文件名、行号等信息。这样,当程序崩溃或者发现内存泄漏时,就能迅速定位到问题代码。这比纯粹依赖调试器或操作系统工具要灵活和定制化得多。
还有就是性能优化。有些时候,特定的数据结构或者算法对内存的访问模式有特殊要求,比如需要内存对齐到某个特定的字节边界,或者需要将相关数据放在缓存行中。标准库的
new和
delete可能无法满足这些细致的需求。通过重载,我们可以调用底层的
aligned_alloc或直接与操作系统API交互,确保内存分配符合我们的高性能需求。
当然,也有一些更高级的用法,比如绑定到特定硬件或内存区域,像GPU内存、共享内存或者NUMA架构下的本地内存。这些就不是日常开发能遇到的了,但确实是重载能力的一种体现。总之,核心目的就是:当默认的内存管理机制不够用、效率低下或者无法满足特定需求时,重载就成了我们手中的利器。
重载operator new时有哪些常见的陷阱和注意事项?
我记得有一次,就是因为没注意递归调用,直接把程序跑崩了,那感觉真是一言一言难尽。所以,重载这玩意儿,坑是真不少,得小心翼翼。
首先,最常见的陷阱就是递归调用。如果你在自定义的
operator new或
operator delete内部,不小心又使用了
new或
delete关键字来分配/释放内存,那恭喜你,你已经成功创建了一个无限递归的黑洞。正确的做法是,如果你需要底层内存分配,必须显式地调用全局的
::operator new、
::operator delete,或者更底层的C函数如
std::malloc和
std::free。记住那个
::,它很重要,意味着你是在调用全局命名空间下的版本。
其次,异常安全是另一个大问题。
operator new在内存分配失败时,标准行为是抛出
std::bad_alloc异常。如果你使用
std::malloc,它在失败时返回
nullptr。那么你的自定义
operator new就必须检查这个
nullptr,并在必要时抛出
std::bad_alloc,以保持与标准行为的一致性。
operator delete则不同,它不应该抛出异常,因此通常会加上
noexcept关键字。
再来是
size_t size参数的含义。
operator new接收的
size参数是编译器计算出的,用于存储对象及其所有相关开销(比如虚函数表指针、数组大小信息等)所需的总字节数。你不能简单地认为它就是你类的大小。特别是对于数组
operator new[],这个
size会更大,因为它可能包含了数组元素数量的元数据。你分配的内存必须至少有这么多字节。
内存对齐也是一个不容忽视的细节。
operator new返回的内存地址必须保证能够正确存储任何类型的对象。这意味着它必须满足所有基本类型的对齐要求,通常是
alignof(std::max_align_t)。如果你直接使用
std::malloc,它通常能保证足够的对齐,但如果自己实现更底层的分配,就需要使用
std::aligned_alloc或其他平台特定的对齐函数。
最后,
operator new和
operator delete必须成对出现。如果你重载了
operator new,那么对应的
operator delete也应该重载,并且它们的实现逻辑必须是互补的。比如,如果
operator new从一个内存池中取内存,那么
operator delete就应该将内存归还到那个内存池。否则,你可能会导致内存泄漏或者双重释放等问题。尤其是在全局重载时,这种成对出现的原则更要严格遵守,因为任何一个环节出错都可能影响整个程序的稳定性。 如何实现一个简单的类级别内存池?
这块儿说起来复杂,但核心思想就是“以空间换时间”,或者说“预先准备好弹药”。实现一个简单的类级别内存池,通常是维护一个空闲内存块的链表(Free List)。当需要分配内存时,就从链表里取;当释放内存时,就把它加回链表。
下面是一个非常简化版的实现思路和代码:
#include <iostream> #include <vector> #include <mutex> // 考虑线程安全 // 假设我们有一个要使用内存池的类 class PooledObject { public: int id; double value; PooledObject(int i = 0, double v = 0.0) : id(i), value(v) { // std::cout << "PooledObject constructor: " << id << std::endl; } ~PooledObject() { // std::cout << "PooledObject destructor: " << id << std::endl; } // --- 内存池相关成员 --- private: // 指向下一个空闲块的指针 // 注意:这个指针会占用空闲块的内存,所以它必须能容纳一个指针 // 并且在对象实际被构造时,这部分内存会被对象成员覆盖 PooledObject* nextFreeBlock; static PooledObject* s_freeList; // 空闲链表头 static const size_t BLOCK_SIZE = sizeof(PooledObject); // 每个内存块的大小 static const size_t CHUNK_SIZE = 10; // 每次向系统申请的块数 static std::mutex s_mutex; // 线程安全锁 public: // 重载 operator new static void* operator new(size_t size) { if (size != BLOCK_SIZE) { // 如果请求的大小与我们池化对象的大小不符,则回退到全局 new // 这很重要,因为可能存在继承或虚函数表等额外开销 return ::operator new(size); } std::lock_guard<std::mutex> lock(s_mutex); // 保证线程安全 if (s_freeList == nullptr) { // 空闲链表为空,需要向系统申请新的内存块 std::cout << "Memory pool exhausted, allocating new chunk of " << CHUNK_SIZE << " objects." << std::endl; // 申请一大块内存,然后将其切割成小块并加入空闲链表 char* newChunk = static_cast<char*>(::operator new(BLOCK_SIZE * CHUNK_SIZE)); if (!newChunk) { throw std::bad_alloc(); } for (size_t i = 0; i < CHUNK_SIZE; ++i) { PooledObject* block = reinterpret_cast<PooledObject*>(newChunk + i * BLOCK_SIZE); block->nextFreeBlock = s_freeList; s_freeList = block; } } // 从空闲链表头部取出一个块 PooledObject* blockToUse = s_freeList; s_freeList = s_freeList->nextFreeBlock; // 移动链表头 std::cout << "Allocated from pool at: " << blockToUse << std::endl; return blockToUse; } // 重载 operator delete static void operator delete(void* ptr) noexcept { if (ptr == nullptr) return; // 简单检查,如果不是我们池化的对象大小,回退到全局 delete // 实际应用中需要更严谨的判断,例如记录池化内存的范围 // 这里只是为了演示,假设所有 PooledObject 都通过池分配 // 如果是从 ::operator new 分配的,则应该用 ::operator delete 释放 // 这是一个简化,实际情况需要更复杂的判断逻辑 // 例如,可以维护一个std::set来记录所有池化分配的地址 // 但那样会增加开销,所以通常是约定好,只有特定大小的对象才走池 // 为了演示,我们假设所有大小为 BLOCK_SIZE 的对象都走池 // 这是一个潜在的bug来源,因为其他类型如果大小碰巧一样,也可能被误处理 // 更好的做法是,在new时标记这块内存是来自池的,或者直接限制只有本类才用池 std::lock_guard<std::mutex> lock(s_mutex); // 保证线程安全 PooledObject* blockToReturn = static_cast<PooledObject*>(ptr); blockToReturn->nextFreeBlock = s_freeList; // 将块放回空闲链表头部 s_freeList = blockToReturn; std::cout << "Returned to pool: " << ptr << std::endl; } // TODO: 考虑 operator new[] 和 operator delete[] 的实现 // 对于内存池,通常只针对单个对象,数组的池化会复杂很多 }; // 初始化静态成员 PooledObject* PooledObject::s_freeList = nullptr; std::mutex PooledObject::s_mutex; // int main() { // std::cout << "--- Testing PooledObject Memory Pool ---" << std::endl; // // std::vector<PooledObject*> objects; // for (int i = 0; i < 15; ++i) { // objects.push_back(new PooledObject(i, i * 1.1)); // } // // for (PooledObject* obj : objects) { // delete obj; // } // // std::cout << "\n--- Allocating again to see reuse ---" << std::endl; // PooledObject* obj1 = new PooledObject(100); // PooledObject* obj2 = new PooledObject(200); // delete obj1; // delete obj2; // // return 0; // }
这个例子中,
PooledObject::s_freeList是核心,它是一个指向
PooledObject类型(但实际上是空闲内存块)的指针链表。当
new PooledObject被调用时,
operator new会检查
s_freeList。如果链表非空,就取出一个块;如果为空,它会一次性向系统申请一个
CHUNK_SIZE大小的内存块,然后将这些新块切割并添加到
s_freeList中。
operator delete则
以上就是如何重载C++类的operator new和operator delete的详细内容,更多请关注知识资源分享宝库其它相关文章!
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。