C++ allocator 类的使用

本文详细介绍了C++中allocator类的使用,如何解决new操作中内存分配与对象构造分离的问题,通过实例展示了如何利用allocator进行内存分配、对象初始化和释放,包括vector的uninitialized_copy和uninitialized_fill功能的演示。

C++ allocator 类的使用

1. 用来解决的问题

allocator类主要是用来解决new的一些缺点的。比如,有时候我们申请了一整块的内存但是又不想初始化的时候,new是没办法做到的。比如:

string * ptr = new string[100]

new在构造的过程中同时调用了100次string的默认构造函数将将100个string给初始化了。而我们需要的可能是3个string,而且等到需要用的时候再进行初始化,这样效率比较高。因此,产生了allocator类,用来把"内存分配" 和“对象构造”两个过程分离开来。 — <c++primer 5th p.427>

2.allocator的使用方式

#include <iostream>
#include <memory>  // 注意allocator类定义在memory头文件中
#include <string>
#include <vector>
using namespace std;


int main() {
   
   

	// 初始化一个allocator对象a
	allocator<string> a;

	// 由a分配出可以容纳20个string的一块原始地址
	string
### C++Allocator使用方法及示例 #### 基本概念 AllocatorC++ 标准模板库 (STL) 提供的一种机制,用于管理和分配容器使用的内存。通过分离内存管理逻辑与数据结构本身的设计,提高了代码的灵活性和重用性[^1]。 #### 创建自定义 Allocator 型 为了创建一个支持特定型的 allocator,可以继承 `std::allocator` 或者实现自己的版本: ```cpp template<typename T> class MyAlloc : public std::allocator<T> { public: using size_type = typename std::allocator<T>::size_type; using pointer = typename std::allocator<T>::pointer; template<typename U> struct rebind { typedef MyAlloc<U> other; }; // 构造函数和其他必要成员... }; ``` #### 定义带有自定义 Allocator 的容器 当希望某个 STL 容器使用不同的 allocator 时,在声明该容器时指定第二个模板参数即可: ```cpp typedef std::vector<int, MyAlloc<int>> IntVector; IntVector myVec; ``` #### 手动管理内存空间 对于更复杂的场景,可能需要直接控制对象生命周期以及它们占用的空间。下面展示了一个简单的例子,其中包含了动态分配数组并初始化元素的过程[^2]: ```cpp #include <memory> struct Example { int data; }; int main() { const auto numElements = 5; // 获取默认allocator实例 std::allocator<Example> alloc; // 分配未构造的对象存储位置 auto* rawMemory = alloc.allocate(numElements); try { // 对每个位置执行placement new来构建对象 for(size_t i=0 ;i<numElements;++i){ new(rawMemory+i) Example{static_cast<int>(i)}; } // 访问这些已构造好的对象 for(auto& elem:*rawMemory){ printf("%d ",elem.data); } // 销毁所有对象 for(size_t i=0;i<numElements;++i){ (rawMemory+i)->~Example(); } } catch(...) { // 如果发生异常,则释放之前分配的所有资源 while(numElements--){ if((rawMemory+numElements)->data != 0) (rawMemory+numElements)->~Example(); } throw; } // 解除对原始内存块的占有权 alloc.deallocate(rawMemory,numElements); } ``` 此程序展示了如何利用 allocator 来获取一块连续的内存区域,并通过 placement-new 显式地在其上放置多个对象;最后记得清理现场以防止泄漏。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值