zoukankan      html  css  js  c++  java
  • C++--allocator类的使用

    C++为我们提供了安全的内存空间申请方式与释放方式,可是new与delete表达式却是把空间的分配回收与对象的构建销毁紧紧的关联在一起。实际上,作为与C语言兼容的语言,C++也为我们提供了更加底层的内存操作方式的。

    谈C++就离不开STL,考虑一下vector<>类的机制,为了高效率的添加与删除元素,它并不会在我们每次进行加入或删除操作时进行内存的分配与回收,而是会提前预留下一片空间。我们通过size函数能够得到容器内元素的个数,通过capacity函数则能够得到该容器的实际大小。实际上每一个容器都有自己的Allocator类,用于进行空间的分配与回收,对象的构造与销毁。以下的代码来自与《C++ primer》,是vector类的push_back函数的一种可能实现方式:

    复制代码
    template <class T>
    void Vector<T>::push_back(const T& t)
    {
    // are we out of space?
        if (first_free == end)
    
            reallocate(); // gets more space and copies existing elements to it
    
         alloc.construct(first_free, t);
    
        ++first_free;
    }
    复制代码

    first_free指向容器中第一个空暇的块,假设已经没有空暇块了,则通过reallocate函数又一次分配。alloc是Alloctor<T>类的一个对象,调用其construct方法可在一个指定的区域构建对象,调用的是类型T的拷贝构造函数。在构造完毕之后,让first_free指向下一个空暇块。

    当我们使用new表达式,来调用拷贝构造函数时实际上时伴随着空间的分配的。那么Allocator是怎么做到的呢?实际上它是调用了C++的一个内置的操作符:

    void *operator new(size_t); // allocate an object
    void *operator new[](size_t); // allocate an array
    new (place_address) type
    new (place_address) type (initializer-list)

    这写重载操作符函数能够进行内存的分配以及在指定的内存空间进行对象的构造。须要注意的是它们并不是new表达式,new表达式是不能够被重载的,实际上new表达式底层也就是调用了这些重载函数的。前两个用内存的分配,后两个则用于对象的构造。Alloctor<T>类的construct方法底层实现实际上就是一句调用而已:

    new (first_free) T(const T& t);

    我们再来看一下reallocate函数的实现:

    复制代码
    template <class T> void Vector<T>::reallocate() {
    // compute size of current array and allocate space for twice as many elements
        std::ptrdiff_t size = first_free - elements;
        std::ptrdiff_t newcapacity = 2 * max(size, 1);
    // allocate space to hold newcapacity number of elements of type T
        T* newelements = alloc.allocate(newcapacity);
    // construct copies of the existing elements in the new space
        uninitialized_copy(elements, first_free, newelements);
    // destroy the old elements in reverse order
        for (T *p = first_free; p != elements; /* empty */ )
            alloc.destroy(--p);
    // deallocate cannot be called on a 0 pointer
        if (elements)
    // return the memory that held the elements
            alloc.deallocate(elements, end - elements);
    // make our data structure point to the new elements
        elements = newelements;
        first_free = elements + size;
        end = elements + newcapacity;
    }
    复制代码

    这个实现就略微复杂一点了,逻辑上我就不说了,着重说明一下当中几个函数的使用吧。首先是Alloctor<T>类的allocate成员函数的使用,它的作用是向系统申请指定个数的长度为sizeof(T)的连续空间,其底层实现是:

    return operator new[](newcapacity * sizeof(T));

    uninitialized_copy函数实际上是memory头文件里的一个函数,它的声明形式例如以下:

    template <class InputIterator, class ForwardIterator>
             ForwardIterator
               uninitialized_copy ( InputIterator first, InputIterator last,
                                    ForwardIterator result );

    elements指针指向的是vector内部维护的线性表的首地址,该函数的调用实际上将elements与first_free所限定的区域里的对象复制到由newelements 所指向的新分配的的空间中去,其底层也是使用的是拷贝构造函数。

    然后是关于Alloctor<T>类的destroy成员函数的分析,它有一个參数,指向须要销毁的对象的指针,该函数仅仅进行对象的销毁,但不进行内存的回收。实际上这里就是简单的调用析构函数而已(不要质疑,析构函数确实能够通过指针直接调用的哦)。

    接下来是关于Alloctor<T>类的deallocate成员函数的分析,它有两个參数,第一个指向线性表的首地址,第二个參数指明要内存回收的对象的个数,注意,这里仅仅进行内存回收,而不会进行对象的销毁,其底层使用的是delete重载函数,同new重载函数一样,它也不是我们所熟知的delete表达式,而delete表达式其底层则是调用了delete重载函数来释放内存的,先来看delete有哪些重载函数:

    void *operator delete(void*); // free an object
    void *operator delete[](void*); // free an array

    这两个版本号是分别用来释放单个对象以及数组对象的。

    小结

    C++底层为我们提供了内存分配与回收,对象创建与释放的单独的手段,它们是operator new, placement new, operator delete以及析构函数(不存在placement delete)。通过这四种手段,我们能够灵活的进行资源的合理管理,但它们是属于较低层次的手段,STL为我们提供了Allocator类能非常好的为我们做这一切,所以,如无必要,我们最好使用Allocator类来进行内存的管理。进行这样的级别的内存管理,处理在效率上的提升外,还能有效的降低内存碎片的诞生,这在某些内存资源有限(比如嵌入式设备)的情况下将是一种非常有效的方式。
  • 相关阅读:
    mongo dump
    http请求
    DT-06 For AT
    DT-06 For Homekit
    DT-06 For MQTT
    利用DoHome APP和音箱控制小车的实验参考步骤
    利用DoHome APP和音箱控制LED灯实验参考步骤
    利用DoHome APP和音箱控制继电器通断电实验参考步骤
    HTML5学习笔记1
    HTML5学习第四天
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4242138.html
Copyright © 2011-2022 走看看