gpt4 book ai didi

c++ - forward_list、set、list 等如何调用 std::allocator?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:55 26 4
gpt4 key购买 nike

我注意到分配器只能分配 T 类型的对象并保留大小为 n * sizeof(T) 的内存块. std::list<T> 内部的链表节点然而,类型不一定是 T 类型的对象,它们的大小也不一定与 T 相同对象。那样的话,怎么可能std::list使用 std::allocator分配内存?

最佳答案

这就是为什么 rebind type存在。它允许您创建一个类似的分配器,而不是分配其他东西(例如 node<T>)。

基本上是这样的:

std::allocator<int> int_alloc;
std::allocator<int>::rebind<node<int>> node_alloc;
//Perhaps more useful:
decltype(int_alloc)::rebind<node<int>> node_alloc;

当然,在实际情况下,这一切都将被模板化,但希望这能体现这个想法。

有关更多信息,请阅读注释和示例 here .

关于c++ - forward_list、set、list 等如何调用 std::allocator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20941645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com