C++常见问题总结_动态内存管理类

某些类需要在运行时分配可变大小的内存空间,通常这种类可以使用标准库容器来保存他们的数据。但是这一策略并不是对所有的类都管用,某些类需要自己进行内存分配,这些类一般需要自己定义自己的拷贝控制成员来管理所分配的内存。
这一篇文章将实现vector类的一个简化版本,不采用模板,只适用于string。将其命名为StrVec。
StrVec类:

#pragma once
#define  _SCL_SECURE_NO_WARNINGS
#include<string>
#include<memory>

using namespace std;

class StrVec {
public:
    StrVec() :elements(nullptr), first_free(nullptr), cap(nullptr) {}
    StrVec(initializer_list<string> il);
    StrVec(const StrVec&);
    StrVec&operator=(const StrVec&);
    ~StrVec();
    void push_back(const string&);
    void reserve(size_t n);
    void resize(size_t n);
    void resize(size_t n, const string &s);
    size_t size() const { return first_free - elements; }
    size_t capacity() const { return cap - elements; }
    string *begin() const { return elements; }
    string *end() const { return first_free; }
private:
     allocator<string> alloc;  //分配元素

    void chk_n_alloc()
    {
        if (size() == capacity())
            reallocate();
    }
    pair<string*, string*>alloc_n_copy(const string*, const string*);

    void free();                       //销毁元素并释放内存
    void reallocate();                 //获得更多的内存并拷贝已有的元素
    void reallocate(size_t);           //分配指定的内存
    string *elements;                  //指向数组首元素的指针
    string *first_free;                //指向数组第一个空闲元素的指针
    string *cap;                       //指向数组尾后位置的指针
};

对应的设计:


#include"StrVec.h"
#include<utility>
#include<initializer_list>

void StrVec::push_back(const string&str)
{
    chk_n_alloc();
    alloc.construct(first_free++, str);
}


/*分配足够的内存来保存给定范围的元素,并将这些拷贝到新分配的内存中去,返回新空间的开始位置
和拷贝的尾后位置*/
pair<string*, string*> StrVec::alloc_n_copy(const string*b, const string*e)
{
    auto data = alloc.allocate(e - b);
    return{ data,uninitialized_copy(b,e,data) };
}


/*1、首先destroy元素
  2、然后释放StrVec自己分配的空间
*/
void StrVec::free()
{
    if (elements)
    {
        for (auto p = first_free; p != elements;)
            alloc.destroy(--p);
        alloc.deallocate(elements, cap - elements);
    }
}

//设计的列表初始化
 StrVec::StrVec(initializer_list<string>il)
{
    auto newdata = alloc_n_copy(il.begin(), il.end());
    elements = newdata.first;
    first_free = cap = newdata.second;
}


//我们的StrVec有类值的行为。当我们拷贝和赋值时必须分配独立的内存
StrVec::StrVec(const StrVec&s)
{
    auto newdata = alloc_n_copy(s.begin(), s.end());
    elements = newdata.first;
    first_free = newdata.second;
    cap = newdata.second;
}

StrVec::~StrVec()
{
    free();
}

StrVec&StrVec::operator=(const StrVec&s)
{
    auto data = alloc_n_copy(s.begin(), s.end());
    free();
    elements = data.first;
    first_free = cap = data.second;
    return *this;
}

//调整空间大小,当空间不够时会将容量加倍
 void StrVec::reallocate()
{
    auto newcapacity = size() ? 2 * size() : 1;

    auto newdata = alloc.allocate(newcapacity);

    auto dest = newdata;
    auto elem = elements;
    for (size_t i = 0; i != size(); ++i)
        alloc.construct(dest++, std::move(*elem++));

    free();
    elements = newdata;
    first_free = dest;
    cap = elements + newcapacity;

}

//调整空间为指定数值大小
 void StrVec::reallocate(size_t newcapacity)
{
    auto newdata = alloc.allocate(newcapacity);

    auto dest = newdata;
    auto elem = elements;
    for (size_t i = 0; i != size(); ++i)
        alloc.construct(dest++, std::move(*elem++));

    free();
    elements = newdata;
    first_free = dest;
    cap = elements + newcapacity;

}


 void StrVec::reserve(size_t n)
{
    if (n > capacity())
        reallocate(n);
}

 void StrVec::resize(size_t n)
{
    if (n > size())
    {
        while (size()<n)
        {
            push_back("");
        }
    }
    else if (n < size())
    {
        while (size()>n)
        {
            alloc.destroy(--first_free);
        }
    }
}

 void StrVec::resize(size_t n, const string &s)
{
    if((n>size()))
        while (size()<n)
        {
            push_back(s);
        }
}

对于上述代码的简要说明:
对于allocator及其一些相关的使用可以参考:C++常见问题总结_动态数组
每个StrVec有三个指针成员指向其元素使用的内存:

  • elements,指向分配的内存中的首元素
  • first_free,指向最后一个实际元素之后的位置
  • cap,指向未分配的内存末尾之后的位置
  • alloc类型为allocator分配StrVec使用的内存

此外对于reallocate成员函数需要进行一点说明。reallocate在内存用完时为StrVec类分配新的内存,在重新分配内存的时候,我们为了避免分配和释放string的额外开销,我们使用标准库的move函数。使得可以直接移动原内存的数据到新内存。
最后测试一下StrVec类:

#include<iostream>
#include"StrVec.h"

int main()
{

    StrVec vctr={"hello","qwe","asdas","nihao","chengxu"};

        cout << "所占有的大小:" << vctr.size() << endl;
        cout << "分配的内存: " << vctr.capacity() << endl;
        cout << "vctr元素为:" << endl;
        for (int i = 0; i < vctr.size(); ++i)
            cout << *(vctr.begin() + i) << " ";
        cout << endl;

        vctr.push_back("oops");
        cout << endl;
        cout << "加入一个元素后:" << endl;
        cout << "vctr所占有的大小:" << vctr.size() << endl;
        cout << "vctr分配的内存: " << vctr.capacity() << endl;


        vctr.reserve(50);
        cout << endl;
        cout << "调整之后空间:" << endl;
        cout << "vctr所占有的大小:" << vctr.size() << endl;
        cout << "vctr分配的内存: " << vctr.capacity() << endl;

        vctr.resize(10, "hahha");
        cout << endl;
        cout << "使用resize之后:"<<endl;
        cout << "vctr所占有的大小:" << vctr.size() << endl;
        cout << "vctr分配的内存: " << vctr.capacity() << endl;
        cout << "vctr元素为:" << endl;
        for (int i = 0; i < vctr.size(); ++i)
            cout << *(vctr.begin()+i) << " ";
        cout << endl;


        StrVec vctr_copy = vctr;
        cout << endl;
        cout << "验证拷贝初始化:" << endl;
        cout << "vctr_copy所占有的大小:" << vctr_copy.size() << endl;
        cout << "vctr_copy分配的内存: " << vctr_copy.capacity() << endl;
        cout << "vctr_copy元素为:" << endl;
        for (int i = 0; i < vctr_copy.size(); ++i)
            cout << *(vctr_copy.begin() + i) << " ";
        cout << endl;

        StrVec vctr_copy1;
        vctr_copy1 = vctr_copy;
        cout << endl;
        cout << "验证赋值运算符:" << endl;
        cout << "vctr_copy1所占有的大小:" << vctr_copy1.size() << endl;
        cout << "vctr_copy1分配的内存: " << vctr_copy1.capacity() << endl;
        cout << "vctr_copy1元素为:" << endl;
        for (int i = 0; i < vctr_copy1.size(); ++i)
            cout << *(vctr_copy1.begin() + i) << " ";
        cout << endl;

        getchar();

}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值