当前位置:网站首页>定长内存池
定长内存池
2022-06-26 20:18:00 【FIappy Brid】
写一个定长内存池!
#pragma once
#include <iostream>
using std::cout;
using std::endl;
// 定长内存池!
// template<size_t N>
// class ObjectPool {};
/* 左值 和 右值 左值 : 在 '='左边的,实际是变量的内存所在内容要被覆盖! 右值 : 在 '=' 右边的,实际是变量所在内存的内容要被取出! */
template<class T>
class ObjectPool {
public:
T* New() {
T* obj = nullptr;
if (_freeList) {
// 释放的内存还在! 进行头删!
void* next = *(void**)_freeList; // 指针中的内容给next指针
obj = _freeList;
freeList = next;
new (obj)T;
return obj;
}
if (residualSize < sizeof(T)) {
// 剩余的内存不够分了!
residualSize = 128 * 1024;
_memory = malloc(residualSize); // 再申请一块!
if (_memory == nullptr) {
// 内存申请失败!
throw std::bad_alloc(); // 抛异常,终止程序!
}
}
obj = (T*)_memory; // 切一块内存给他!
// 确保申请的内存可以以链表的形式组织起来!
size_t obj_size = sizeof(T) > sizeof(void*) ? sizeof(T) : sizeof(void*);
_memory += obj_size;
residualSize -= obj_size();
new (obj)T; // 初始化内存!
return obj;
}
void Delete(T* obj) {
// 释放内存!
obj->~T(); // 显示调用对象析构函数!
// 将释放的内存取一个指针大小的空间存放下一个节点的地址!
*(void**)obj = _freeList; // 取obj所指向的内存的前(存下指针长度)的字节的内存做next指针的内存!
_freeList = obj;
}
private:
char* _memory = nullptr; // 申请的内存的首地址!
void* _freeList = nullptr; // 释放内存的链表头指针!
size_t residualSize = 0; // 剩余内存大小!
};
边栏推荐
- 数据库SQL语句撰写
- Nftgamefi chain game system development detailed solution - chain game system development principle analysis
- 慕课11、微服务的用户认证与授权
- C primer plus learning notes - 3. Character IO (input / output)
- Gd32 USB composite device file descriptor
- 【推荐收藏】这8个常用缺失值填充技巧一定要掌握
- Serial port application program based on gd32
- Development of NFT for digital collection platform
- Wechat applet custom pop-up components
- IDEA 报错:Process terminated【已解决】
猜你喜欢

Installation and use of logstash

Boot indicator monitoring

MySQL - subquery usage

好物推薦:移動端開發安全工具

uni-app使用canvas绘制二维码

mysql的充值问题

Unity——Mathf. Similarities and differences between atan and atan2

Database SQL statement writing

On the origin of the dispute between the tradition and the future of database -- AWS series column

回溯思路详解
随机推荐
Unit test of boot
MySQL stored procedure
JS mobile terminal touch screen event
Is it safe to open a securities account? Is there any danger
Dynamic planning 111
Pinda general permission system (day 3~day 4)
Tiktok practice ~ sharing module ~ short video download (save to photo album)
Tiktok practice ~ homepage video ~ pull-down refresh
Arduino UNO + DS1302利用31字节静态RAM存储数据并串口打印
Jsonutils tool class (based on Alibaba fastjson)
C language file cursor fseek
mongoDB的三种基础备份方法
抖音实战~首页视频~下拉刷新
String string is converted to jsonarray and parsed
Tiktok practice ~ sharing module ~ generate short video QR code
MySQL - table creation and management
Tiktok practice ~ sharing module ~ copy short video link
[MySQL series] collection of common working SQL (continuous update)
C语言 文件光标 fseek
Web resource preloading - production environment practice