STL自定义分配器来管理不同的内存空间
我想使用 STL 自定义分配器类的不同实例来管理不同的内存空间,然后能够为 STL 容器指定分配器实例,以便每个容器仅从其分配的内存空间中提取。但我不知道如何才能做到这一点。我了解如何将分配器类型传递到 STL 容器的模板参数中,但我想要类似于将分配器实例传递到 STL 容器的构造函数中的东西。 STL中有没有办法做到这一点?
I would like to use different instances of an STL custom allocator class to manage different memory spaces, and then be able to specify an allocator instance to an STL container such that each container only draws from its assigned memory space. But I don't see how I can do that. I see how I can pass an allocator type into the template parameters of an STL container, but I want something akin to passing an allocator instance into the constructor of an STL container. Is there a way to do this in STL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,STL 分配器不能有状态(或者至少必须非常小心如何使用该状态) - 特定分配器类型的每个实例必须是等效的,STL 容器才能有效地与它们一起工作。我现在不记得细节,但我知道 Scott Meyers 在 “有效的 STL”,第 10 条:了解分配器约定和限制。
但是,您可以拥有与封装在分配器类型中的分配器之间的差异非常相似的模板化分配器,并使用分配器模板的不同“实例化”(每个模板“实例化”是不同的类型) )。再说一遍,我的记忆是迈耶斯非常清楚地讨论了这一点。
例如,请参阅 Anthony Aue 的文章中的此段落,“使用 STL 的自定义池分配器提高性能”:
另请参阅 Stephan T. Lavavej 在 此新闻组主题。
如果其他人在此期间没有提供详细信息,我将在今晚晚些时候更新。
Unfortunately STL allocators cannot have state (or at least have to be very careful how that state is used) - each instance of a particular allocator type must be equivalent for STL containers to work effectively with them. I don't recall the details right now, but I know that Scott Meyers discusses this problem at length in "Effective STL", Item 10: Be aware of allocator conventions and restrictions.
However, you can have templated allocators that are very similar with the differences between the allocators being encapsulated in the allocator type and use different 'instantiations' of the allocator template (each template 'instantiation' is a different type). Again, my recollection is that Meyers discusses this pretty clearly.
For example see this paragraph from an article by Anthony Aue, "Improving Performance with Custom Pool Allocators for STL":
See also Stephan T. Lavavej's discussion in this newsgroup thread.
I'll update later tonight if someone else doesn't give the details in the meantime.
STL 容器允许您将分配器作为参数传递给构造函数。
例如,以下是向量的适当构造函数:
默认情况下,它们仅使用默认构造的分配器。
The STL containers allow you to pass the allocator in as an argument to the constructor.
For example here are the appropriate constructors for vector:
By default, they just use a default constructed allocator.
也许您可以编写一组分配器类型,其中包含指向单独内存空间的静态指向。
然后,当STL容器构造其分配器时,分配器使用分配给该分配器的内存空间。
为简单起见,假设您要使用两个内存空间。创建两种分配器类型,每个空间一种。根据需要将分配器类型传递给 STL 容器构造函数。
Perhaps you could code a set of allocator types which contains a static pointing to seperate memory spaces.
Then, when the STL container constructs its allocator, the allocator uses the memory spaceassigned to that allocator.
For simplicity, assume you want to use two memory spaces. Create two allocator types, one for each space. Pass the allocator type to the STL container constructors as required.