我刚刚学习 C++ 分配器,我试图理解的目的struct rebind
在每个分配器中。例如,在这个程序 https://msdn.microsoft.com/en-us/library/5fk3e8ek.aspx:
#include <memory>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef vector<int>::allocator_type IntAlloc;
int main( )
{
IntAlloc v1Iter;
vector<int> v1;
//************What's going on here?********
IntAlloc::rebind<char>::other::pointer pszC =
IntAlloc::rebind<char>::other(v1.get_allocator()).allocate(1, (void *)0);
int * pInt = v1Iter.allocate(10);
}
我试图理解关键线在做什么。是否修改了typedef
IntAlloc
现在服务器作为分配器char
vector
?即使我猜对了,我也不确定我能不能破解它。这是我的猜测:
IntAlloc::rebind<char> //accessing the struct rebind
`::other` //accessing data member other inside rebind
(v1.get_allocator()) //**isn't this just retrieving IntAlloc in its original form?**
///What is this for?
.allocate(1, (void *)0); //**this is allocating something? What do these parameters mean?**
不幸的是,这都是 C++11 分配器之前的工作,他们使用 2011 标准极大地简化了事情。
struct rebind
本质上是一种绕过语言中没有模板化类型定义这一事实的方法,而这是Container
不会在内部分配与您传递给它们的分配器相同的类型。它们“重新绑定”分配器并返回一个可以分配不同类型的新分配器(例如,“std::set”分配一些“Node”类型,该类型具有指向树结构的其他节点的指针,此外还有一个对象您的分配器分配的类型)。这种机制隐藏了内部结构,但肯定不漂亮。
例如,您可能有一个Allocator<int>
,但是要制作树结构,std::set
需要从类型的对象分配Allocator<std::_Node<int>>
或类似的东西。这rebind
机制允许这样做。
(v1.get_allocator()) //这不是只是以原始形式检索 IntAlloc 吗?
这是从获取分配器对象v1
,其类型为vector<int>::allocator_type
,所以或多或少是的。
IntAlloc::rebind<char>::other(v1.get_allocator())
正在得到一个char
分配器,并初始化它以使用来自vector<int>
, v1
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)