STL allocator 类探究
来源:互联网 发布:安康市 软件正版 编辑:程序博客网 时间:2024/06/11 20:18
- 什么是 allocator 类
- 一个例子
- allocator 类有什么用
什么是 allocator 类?
allocator
类的功能是用来分配无初始化的内存,但是这段内存,其初始化的形式已经确定。
一个例子
#include <memory>#include <iostream>using namespace std;class Example {public: Example() { cout << "example default constructor:" << endl; } Example(int num) { m_num = num; cout << "example constructor:" << m_num << endl; }private: int m_num;};int main(int argc, char* argv[]){ allocator<Example> exampleAllocator; // 操纵内存空间的钥匙 int count = 10; auto p = exampleAllocator.allocate(count); // 分配空间 for(auto i = 0; i != count; ++i) { exampleAllocator.construct(p++, i); // 构造对象 } for(auto i = 0; i != count; ++i) { exampleAllocator.destroy(--p); // 销毁对象 } exampleAllocator.deallocate(p, count); // 收回内存 return 0;}
可以看到,exampleAllocator.allocate(count)
这一步只是分配了 n 个大小的空间并返回了指向这段空间的头指针。
调用 construct
方法带入指针和构造所需要的参数对这段内存进行初始化。
调用 destroy
方法带入指针来析构这个指针所指内存中的内容。
调用 deallocate
方法带入空间起始指针 p 和对象个数来回收从 p 开始这 n 个对象大小的空间。
allocator 类有什么用?
allocator
将类对象的空间分配与构造、解析与回收这两组功能分解开了。allocator
分配的空间是未经过初始化的原始内存空间,通过constructor
来进行按需构造。- 在存储体积较大的对象的容器中,这会很有用,因为毕竟体积大的对象其反复构造和拷贝的代价也是很大的。
allocator
分配的空间可以解析不回收,解析之后仍然可以按照原本的类型继续构造,当然也可以用歪门邪道扭转指针类型,比如说这样子:
int main(int argc, char* argv[]){ allocator<Example> exampleAllocator; int count = 10; auto ptr = exampleAllocator.allocate(count); int* i_p = (int*)(void*)ptr; // 扭转成空指针类型,然后再扭转成 int* 类型 for(auto i = 0; i != count; ++i) { *i_p++ = i; } for(auto i = 0; i != count; ++i) { cout << *--i_p << endl; } return 0;}
CSDN 辣鸡 MD 编辑器,无序列表格式全丢
阅读全文
0 0
- STL allocator 类探究
- STL中allocator类
- STL Allocator
- STL-allocator
- stl allocator
- STL Allocator
- STL Allocator
- STL Allocator
- STL Allocator
- g++ 中的stl allocator
- stl allocator实现代码
- 关于STL Allocator
- 深入理解 STL allocator
- C++ STL allocator
- STL的默认allocator
- 关于STL allocator
- 详解STL中的allocator
- [STL]源码分析:allocator
- 组合数学学习
- Wireless Network
- 计算机图形学(四)几何变换_5_三维空间的几何变换
- R极简教程-3:R及RStudio的安装
- 设计模式之原型模式的学习思考
- STL allocator 类探究
- _itoa_s出错的问题
- JavaMail实现邮箱验证码
- openstack 常见问题及解决方法
- 字符串相关工具类
- Ubuntu16.04安装后要做的一些事情
- 2、STM32基本接口驱动--IO 单总线 串口 SPI IIC
- 【HTML5入门】Jquery中获取控件值的三种方法
- Jquery.DataTable使用