解析分配器::重新绑定调用 [英] Parsing allocator::rebind calls

查看:88
本文介绍了解析分配器::重新绑定调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习C ++分配器,我试图理解 struct rebind 在每个分配器的目的。例如,在此计划中:

I am just learning about C++ allocators, and I am trying to understand the purpose of the struct rebind in every allocator. For example, in this program:

#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 矢量?即使我猜到了,我不知道我可以打破它。这是我的猜测:

I am trying to understand what the key line is doing. Is it modifying the typedef IntAlloc to now server as an allocator for a char vector? Even if I have guessed correctly, I am not sure I can break it down. Here's my guess:

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?**


推荐答案

struct rebind 本质上是一种方法来避开在语言中没有模板化typedef的事实,这些是 Container 所需要的,它们不在内部分配与分配器相同的类型你传递他们。他们重新绑定分配器并获得一个新的分配器,它可以分配一个不同的类型(例如,'std :: set'分配一些Node类型,它具有指向树结构的其他节点的指针,您的分配器分配的类型)。这个机制隐藏了内部结构,但肯定不漂亮。

struct rebind is essentially a way to get around the fact that there aren't templated typedefs in the language, which are needed by Containers that don't allocate the same type internally as the allocator that you pass them. They "rebind" the allocator and get back a new allocator that can allocate a different type (for example, 'std::set's allocate some 'Node' type that has pointers to other Nodes for a tree structure, in addition to an object of the type your allocator allocates). This mechanism hides the internal structure, but sure isn't pretty.

例如,你可能有一个 Allocator< int> ,但是为了形成树结构, std :: set 需要从类型 Allocator< std :: _ Node& int>> 或类似的东西。 rebind 机制允许。

So for example, you might have an Allocator<int>, but to make a tree structure, std::set needs to allocate from an object of type Allocator<std::_Node<int>> or something like that. The rebind mechanism allows that.


(v1.get_allocator 不是只是检索IntAlloc的原始形式?

code> v1 ,其类型为向量< int> :: allocator_type ,所以或多或少是

This is getting the allocator object from v1, which is of type vector<int>::allocator_type, so more or less yes.

IntAlloc :: rebind< char> :: other(v1.get_allocator())正在获取 分配器,并初始化它以使用向量< int> v1

IntAlloc::rebind<char>::other(v1.get_allocator()) is getting a char allocator, and initializing it to use the allocator from the vector<int>, v1.

这篇关于解析分配器::重新绑定调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆