Jac*_*ian 5 c++ memory-management
我对C ++内存管理非常陌生,但想让我不厌其烦地构建一个简单的分配器,该分配器可以预先为某些容器预先分配足够的内存。
我看过Alexandrescu Loki图书馆并尝试阅读一些博客,但是所有这些只是让我难以理解。我想从一些原始且可行的起点入手,对其进行扩展,然后看它如何演变。这就是我现在所拥有的以及我真正理解的(我的出发点):
template <class T>
struct Allocator {
Allocator(){};
template <class U>
Allocator(Allocator<U> const&);
T* allocate(size_t s) {
return static_cast<T*>(::operator new(s * sizeof(T)));
}
void deallocate(T* p, size_t s) {
::operator delete(p);
}
void construct(T* p, T const& val) {
::new((void *)p) T(val);
}
void destroy(T* p) {
return ((T *) p)->~T();
}
using value_type = T;
};
Run Code Online (Sandbox Code Playgroud)
因此,我现在可以像这样使用它:
std::vector<int, Allocator<int> > vec;
Run Code Online (Sandbox Code Playgroud)
这个分配器非常简单,我理解它的作用。现在,我想对其进行一点扩展,以便我的客户端代码如下所示:
std::vector<int, Allocator<int, 8> > vec;
Run Code Online (Sandbox Code Playgroud)
现在,我希望代码为8个元素分配足够的内存。我尝试使用以下几行扩展我的起始代码:
template <class T, size_t T_num_els>
struct Allocator {
template <class U, size_t U_num_els>
Allocator(Allocator<U, U_num_els> const&);
... I keep all the rest without changes just for testing reason
Run Code Online (Sandbox Code Playgroud)
但是当我编译它时,我得到了错误消息的疯狂列表,一些消息告诉您必需的替换,rebind_alloc和没有名为“ type”的类型。因此,我该如何解决。我应该对垫脚石代码进行哪些更正,以使分配器具有两个模板参数?
我认为问题在于您有一个非类型模板参数。适配器似乎不支持这一点allocator_traits。
有些容器,例如std::list<int>,不会分配ints,但有一些internal_node<int>. 所以它必须能够将 an 转换Allocator<int>为 an Allocator<internal_node<int>>。
要为此类类型 T 创建分配器,allocator_traits期望能够Alloc::rebind<T>::other从原始 (C++98) 分配器接口执行操作,或者Alloc<T, Args...>在分配器为Alloc<U, Args...>.
这两个选项都不符合您的Allocator. 最后一个失败,因为该值8不是可以匹配的类型Args。
也许你可以通过添加来解决这个问题
template<class U>
struct rebind
{
using other = Allocator<U, T_num_els>;
};
Run Code Online (Sandbox Code Playgroud)