文章目录

  • allocator内存管理器
    • 基本属性
    • 类的设计
    • 关键功能的实现
    • 完整的内存管理器
  • 内存管理器的测试:设计自定义的String类。

前情回顾:
allocator内存管理类

allocator内存管理器

某些类需要在运行时分配可变大小的内存空间,一般来说我们使用容器如vector来管理我们的数据,但是对于某些类,在有些时候我们需要自己进行内存的分配。这些类必须定义自己的拷贝控制成员来管理所分配的内存。

我们将实现一个vector,这个vector保存的是sring类型的数据,而且使用我们自己创建的内存分配的方式。我们的这个类叫做 vecStr


基本属性

我们在自己创建的vecStr中需要有三个属性,分别是:

  • element: 指向分配的内存的起始位置。
  • first_free:指向已经构造完成的对象的下一个位置,即未构造的内存的起始位置。
  • cap:总的内存空间的尾后位置。

如图所示:

类的设计


基本构造函数:

strVec();
strVec(std::initializer_list<std::string> initList);
~strVec();
strVec(const strVec& other);            //拷贝构造函数
strVec& operator=(const strVec& other);    //拷贝赋值运算符

以下几个具有关键功能的函数:

  • alloc_n_copy:分配内存,并且拷贝给定范围的元素到一个新的内存中。
std::pair<std::string*, std::string*> alloc_n_copy(const std::string* beg, const std::string* end);
  • reallocate: 当内存不够时,重新分配一块新的内存,并且拷贝原始内容,释放旧的内存
void reallocate();
  • free:释放内存空间
//释放内存
void free();
  • check_n_alloc:检查当前内存空间是否足够,不够的话调用reallocate重新分配一块内存。
//检查内存是否足够,不够的话就重新分配
void check_n_alloc();

其他功能性函数:

//获取总容量
size_t capacity()const { return cap - element; }
//获取已分配的容量大小
size_t size()const { return first_free - element; }
void push_back(const std::string& str);

关键功能的实现


  • alloc_n_copy:接受一个开始位置和结束的位置的指针,开辟一块新的内存空间,并且把开始位置到结束位置中的内容拷贝到这块新的内存空间,并且返回这块内存空间的初始位置和尾后位置。

我们使用pair来保存这两个位置。

std::pair<std::string*, std::string*> strVec::alloc_n_copy(const std::string* beg, const std::string* end)
{auto p = allocStr.allocate(end - beg);        //分配end - beg个大小的内存空间,返回未构造的初始的位置//拷贝内存到新的内存空间,uninitialized_copy返回拷贝结束后的位置,这个位置就是first_free的位置,p就是element的位置return { p,std::uninitialized_copy(beg, end, p) };
}

使用uninitialized_copy来拷贝beg到end的内存空间的内容到新的内存空间p中。


  • reallocate:旧内存空间不够时,我们重新开辟一块内存,并且把原始内容拷贝到新内存中,注意我们的新内存一般是原始内存的两倍大小。
  1. 使用move的进行移动构造,从而避免拷贝构造(拷贝后销毁)的繁琐操作,直接进行指针所有权的转移即可,这就是移动构造函数。
  2. 使用construct构造对象。
  3. 注意属性的更新,element first_free cap此时都指向了新的内存空间的对应位置。
void strVec::reallocate()
{/*在重新分配空间的时候,移动而不是拷贝构造*///申请两倍的空间auto NewSpace = (size() == 0) ? 1 : 2 * size();//分配新内存auto pNew = allocStr.allocate(NewSpace);auto dest = pNew;auto old = element;for (size_t i = 0; i != size(); i++){//移动构造旧的内存里的数据,移动到新的内存空间里allocStr.construct(dest++, std::move(*old++));}free();    //释放旧内存//更新数据element = pNew;first_free = dest;cap = element + NewSpace;
}

  • free:释放旧的内存空间,我们使用三种方法来释放旧的内存空间,for_each函数式,正序销毁和逆序销毁,注意,销毁只是调用了他们的析构函数,我们一定最后使用deallocate来彻底释放这块内存。
void strVec::free()
{if (element){#if 0//for_each销毁std::for_each(begin(), end(), [&](std::string& str){allocStr.destroy(&str);});
#elif 0//逆序销毁旧元素/*for (auto eleBeg = first_free; eleBeg != element;){allocStr.destroy(--eleBeg);}*/
#else//正序销毁旧元素for (auto elebeg = element; elebeg != first_free;){allocStr.destroy(elebeg++);}
#endifallocStr.deallocate(element, cap - element);}
}

完整的内存管理器

#pragma once
#include <iostream>
#include <vector>
#include <memory>
#include <vld.h>
#include <algorithm>/*
内存管理器
*/
class strVec
{public:strVec();strVec(std::initializer_list<std::string> initList);~strVec();strVec(const strVec& other);            //拷贝构造函数strVec& operator=(const strVec& other);    //拷贝赋值运算符//总容量size_t capacity()const { return cap - element; }//已分配的容量size_t size()const { return first_free - element; }void push_back(const std::string& str);//分配至少能容纳n个元素的内存空间void reserve(const int& n);//重新调整大小void resize(const int& n, const std::string& str = "None");
public:std::string* begin()const { return element; }std::string* end()const { return first_free; }
private://分配内存,并且拷贝元素到这个范围里std::pair<std::string*, std::string*> alloc_n_copy(const std::string* beg, const std::string* end);//释放内存void free();//检查内存是否足够,不够的话就重新分配void check_n_alloc();//内存不够,分配新的内存空间:需要拷贝原来的元素并且释放原来的内存void reallocate();void reallocate(int n);
private:std::allocator<std::string> allocStr; //内存分配器std::string* element;        //内存空间的起始元素std::string* first_free; //已分配的实际元素之后的位置std::string* cap;            //总的分配空间之后的位置
};strVec::strVec():element(nullptr), first_free(nullptr), cap(nullptr)
{}strVec::strVec(std::initializer_list<std::string> initList)
{//分配合适的内存大小int n = initList.size();auto p = allocStr.allocate(n);element = first_free = p;cap = p + n;for (auto& xStr : initList){allocStr.construct(first_free++, xStr);}
}strVec::~strVec()
{free();
}strVec::strVec(const strVec& other)
{//拷贝构造,other的内存拷贝到新的对象中auto pPair = alloc_n_copy(other.element, other.first_free);element = pPair.first;first_free = pPair.second;cap = pPair.second;          //alloc_n_copy分配的空间恰好容纳给定的元素
}strVec& strVec::operator=(const strVec& other)
{//赋值运算符,直接对自身操作,返回自身,记得销毁原来的内存auto pPair = alloc_n_copy(other.element, other.first_free);free();element = pPair.first;first_free = cap = pPair.second;// TODO: 在此处插入 return 语句return *this;
}void strVec::push_back(const std::string& str)
{//插入元素check_n_alloc(); //检查空间大小//构造对象allocStr.construct(first_free++, str);
}void strVec::reserve(const int& n)
{//如果n小于等于当前容量,则什么也不做if (n > capacity()){//重新分配reallocate(n);}
}void strVec::resize(const int& n, const std::string& str)
{if (n < capacity()){//如果说缩小容量,则删除后面的元素int m = capacity() - n;       //容量差值 15-10=5 则删除后五个元素for (int i = 0; i < m; i++){allocStr.destroy(--first_free);}cap = first_free;}else{//否则增大容量,末尾填充strreallocate(n);while (first_free != cap){allocStr.construct(first_free++, str);}}
}std::pair<std::string*, std::string*> strVec::alloc_n_copy(const std::string* beg, const std::string* end)
{auto p = allocStr.allocate(end - beg);        //分配end - beg个大小的内存空间,返回未构造的初始的位置//拷贝内存到新的内存空间,uninitialized_copy返回拷贝结束后的位置,这个位置就是first_free的位置,p就是element的位置return { p,std::uninitialized_copy(beg, end, p) };
}void strVec::free()
{if (element){#if 0//for_each销毁std::for_each(begin(), end(), [&](std::string& str){allocStr.destroy(&str);});
#elif 0//逆序销毁旧元素/*for (auto eleBeg = first_free; eleBeg != element;){allocStr.destroy(--eleBeg);}*/
#else//正序销毁旧元素for (auto elebeg = element; elebeg != first_free;){allocStr.destroy(elebeg++);}
#endifallocStr.deallocate(element, cap - element);}
}void strVec::check_n_alloc()
{//内存不够if (size() == capacity()){reallocate();}
}void strVec::reallocate()
{/*在重新分配空间的时候,移动而不是拷贝构造*///申请两倍的空间auto NewSpace = (size() == 0) ? 1 : 2 * size();//分配新内存auto pNew = allocStr.allocate(NewSpace);auto dest = pNew;auto old = element;for (size_t i = 0; i != size(); i++){//移动构造旧的内存里的数据,移动到新的内存空间里allocStr.construct(dest++, std::move(*old++));}free();    //释放旧内存//更新数据element = pNew;first_free = dest;cap = element + NewSpace;
}void strVec::reallocate(int n)
{auto NewSpace = n;//分配新内存auto pNew = allocStr.allocate(NewSpace);auto dest = pNew;auto old = element;for (size_t i = 0; i != size(); i++){//移动构造旧的内存里的数据,移动到新的内存空间里allocStr.construct(dest++, std::move(*old++));}free();   //释放旧内存//更新数据element = pNew;first_free = dest;cap = element + NewSpace;
}

内存管理器的测试:设计自定义的String类。

/*
char* 类型的内存分配器
*/class String
{public:String();String(const char* str);String(const String& other);String& operator=(const String& other);~String();size_t size() const { return end - element; }//重新分配内存
public:private:void free();std::pair<char*, char*> alloc_n_copy(const char* beg,const char* end);//void reallocapacity();char* element;char* end;std::allocator<char> alloCh;   //内存分配器
};int main()
{String s{"woaini"};String s1{ s };String s2;s2 = s1;return 0;
}String::String():element(nullptr),end(nullptr)
{}String::String(const char* str)
{//分配内存int len = strlen(str);auto pStr =  alloc_n_copy(str, str + len);element = pStr.first;end = pStr.second;
}String::String(const String& other)
{auto pNew = alloc_n_copy(other.element, other.end);element = pNew.first;end = pNew.second;
}String& String::operator=(const String& other)
{auto pNew = alloc_n_copy(other.element, other.end);free();element = pNew.first;end = pNew.second;return *this;
}String::~String()
{free();
}void String::free()
{if (element){std::for_each(element, end, [&](char& str){alloCh.destroy(&str);});alloCh.deallocate(element, end - element);}
}std::pair<char*, char*> String::alloc_n_copy(const char* beg, const char* end)
{auto p =  alloCh.allocate(end - beg);return { p,std::uninitialized_copy(beg,end,p) };
}

C++ allocator设计内存管理器相关推荐

  1. 大内高手 内存管理器

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! 大内高手 ...

  2. 大内高手—内存管理器

    大内高手-内存管理器 转载时请注明出处和作者联系方式:http://blog.csdn.net/absurd 作者联系方式:李先静 <xianjimli at hotmail dot com&g ...

  3. 深入研究glibc内存管理器原理及优缺点

    最近查清了线上内存占用过大和swap使用频繁的原因:由于linux使用的glibc使用内存池技术导致的堆外内存暴增,基于这个过程中学习和了解了glibc的内存管理原理,和大家分享,如有错误请及时指出. ...

  4. 内存管理器(十)kernel内存管理----数据结构

    内存管理器(十) kernel内存管理----概况与数据结构 前言 正式开始学习内核的内存管理了,先学习下接口函数,每一个例字都必须写内核模块实验,然后深入到函数的内部研究源码,最后写写练习的小程序. ...

  5. 内存管理器(二)边界标识法

    边界标识算法 前言 首先说明,我们这里的内存管理器主要是以模拟各种内存分配算法为主,从内存申请一片内存然后根据我们所选定的数据结构和算法,实现程序的堆空间的分配,至于内存分配详情我们会在Linux内核 ...

  6. 一个简单而强大的单片机内存管理器-不带内存碎片整理

    单片机简单内存管理器 本代码基于无操作系统的STM32单片机开发.功能强大.可申请到地址空间连续的不同大小的内存空间,且用户接口简单,使用方便 转载请注明出处:http://blog.csdn.net ...

  7. 内存管理器剖析:ptmalloc,windows,macOS

    目录 1. Ptmalloc 2. Windows内存管理器 3. Mac OS内存管理器 4.推荐阅读 核心分析器的优势在于它能够将堆内存解析为数百万个单独的内存块,这些内存块由堆内存管理器分配给应 ...

  8. C/C++内存管理器

    C标准库提供了malloc,free,calloc,realloc,C++标准库还提供了new, new[], delete, delete[].这些用来管理内存,看起来够用了,为啥还要自己写一个内存 ...

  9. flink的内存管理器MemoryManager

    Flink中通过MemoryManager来管理内存. 在MemoryManager中,根据要管理的内存的总量和和每个内存页的大小得到内存页的数量生成相应大小数量的内存页来作为可以使用的内存. pub ...

最新文章

  1. 知乎热议:985计算机视觉研究生找不到工作?
  2. [SimplePlayer] 实现一个简单的播放器
  3. p和li之间的应用上的区别
  4. 【深入Java虚拟机JVM 05】HotSpot对象探秘
  5. 使用Angular可重用Component思路实现一个自带图标(icon)的input控件
  6. PHP分组聊天室--fooking现实
  7. 可替代的C语言开发环境
  8. gem install XXX报错
  9. SSM+物业管理系统 毕业设计-附源码310928
  10. python 自动控制鼠标移动脚本
  11. 已知坐标增量求坐标方位角_全站仪坐标导线测量及平差方法的比较
  12. 深圳LED背光源模组十大生产厂家排名是什么呢
  13. centos xfs硬盘扩容
  14. 冯诺依曼 计算机名言,冯·诺依曼名言
  15. 分布式系统下的纠删码技术之Erasure Code
  16. 微信开发如何优雅的注入token(2)
  17. python读取手机短信信息_python 自动获取手机短信验证码
  18. 推荐系统从入门到接着入门
  19. 计算机原理理解编程语言_计算机如何理解我们对编程语言及其工作原理的高级概述...
  20. hook系统调用(一):爬取MSDN官网上的API调用并改为自己的API(c++正则表达式的应用)

热门文章

  1. Android中的友盟(微信、QQ、新浪)第三方登录分享
  2. spring boot+iview 前后端分离架构之用户管理的实现(三十)
  3. 安卓EventBus使用
  4. 雅可比主对角线(Jacobi diagonalization)化求对称矩阵的特征值(python,数值积分)
  5. 网站在线客服系统怎么添加?
  6. ms project2007 介绍
  7. 在线教你如何设计个性好看的POP字体?
  8. 【Unity2019】利用Vuforia在安卓平台调用UVC相机
  9. 美国产权局关于版权声明格式的说明
  10. 解决红旗linux6SP2 鼠标单击变双击的问题