自定义C++ 容器 内存分配器

查看STL中vector、list源码

template <class _Ty, class _Alloc = allocator<_Ty>>
class vector { // varying size array of values
private:
    template <class>
    friend class _Vb_val;
    friend _Tidy_guard<vector>;

    using _Alty        = _Rebind_alloc_t<_Alloc, _Ty>;
    using _Alty_traits = allocator_traits<_Alty>;
    ...........
template <class _Ty, class _Alloc = allocator<_Ty>>
class list { // bidirectional linked list
private:
    template <class>
    friend class _Hash;
    template <class _Traits>
    friend bool _Hash_equal(const _Hash<_Traits>&, const _Hash<_Traits>&);

    using _Alty          = _Rebind_alloc_t<_Alloc, _Ty>;
    using _Alty_traits   = allocator_traits<_Alty>;
    using _Node          = _List_node<_Ty, typename allocator_traits<_Alloc>::void_pointer>;
    using _Alnode        = _Rebind_alloc_t<_Alloc, _Node>;
    using _Alnode_traits = allocator_traits<_Alnode>;

可以看到STL中vector 和 list的分配器,是采用编译器默认提供的 allocator 分配器。

自定义C++ 容器 内存分配器

  1. 我们可以自己定义容器的分配器,让容器在分配内存的时候,按照我们自己的想法进行。
    代码如下:
#include <iostream>
#include <thread>
#include <vector>
#include <list>
#include <mutex>
#include <chrono>
#include <algorithm>
#include <set>
#include <queue>

using namespace std;

class Xdata
{
public:
    int m_index;
    Xdata()
    {
        cout << "call Xdata()" << endl;
    }
    Xdata(const Xdata& obj)
    {
        this->m_index = obj.m_index;
        cout << "call Xdata(const Xdata& obj)" << endl;
    }
    ~Xdata()
    {
        cout << "call ~Xdata()" << endl;
    }
};

template <typename T>
class MyAllocator
{
public:
    using value_type = T;

    MyAllocator() {}

    template<typename other>
    MyAllocator(const MyAllocator<other>&) {}

    T* allocate(const size_t count)
    {
        cout << "T* allocate(const size_t count)" << endl;
        cout << "typeid(T).name():" << typeid(T).name() << endl;
        return static_cast<T*>(malloc(sizeof(T)*count));
    }

    void deallocate(T* const ptr, const size_t count)
    {
        cout << "void deallocate(T* const ptr, const size_t count)" << endl;
        free(ptr);
    }
};

int main() {

  
    vector<Xdata,MyAllocator<Xdata>> vec;

    Xdata x1;
    x1.m_index = 1;
    vec.push_back(x1);

    cout << "===========================" << endl;

    list<Xdata, MyAllocator<Xdata>> list_data;
    Xdata x2;
    x2.m_index = 2;
    list_data.push_back(x2);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

repinkply

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值