查看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++ 容器 内存分配器
- 我们可以自己定义容器的分配器,让容器在分配内存的时候,按照我们自己的想法进行。
代码如下:
#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;
}