[英]Allocating a collection of std::shared_ptr's for caching
I have a list of elements std::vector<Foo>
which I need to transform into a list of std::shared_ptr<Foo>
's: 我有一个元素列表
std::vector<Foo>
,我需要将其转换为std::shared_ptr<Foo>
的列表:
auto make_shared(const std::vector<Foo>& foos)
{
std::vector<std::shared_ptr<Foo>> result(foos.size());
std::transform(std::begin(foos), std::cend(foos), std::begin(result),
[] (const Foo& foo) { return std::make_shared<Foo>(foo); });
return result;
}
I later use the addresses of the pointed to elements in a cache using a std::unordered_map
. 稍后,我使用
std::unordered_map
在缓存中使用指向元素的地址。 I've found accessing the map to be expensive, and was wondering if I could replace it with a std::vector
given that I know the addresses of all the elements before the first cache lookup: 我发现访问该映射的
std::vector
很大,并且想知道是否可以用std::vector
替换它,因为我知道在第一次缓存查找之前所有元素的地址:
auto complex_calculation(const Foo& foo)
{
const auto idx = std::distance(first_foo_ptr_, std::addressof(foo));
// lookup idx in std::vector...
}
As far as I'm aware, there are two problems with doing this: 据我所知,这样做有两个问题:
std::vector
could be very large. std::vector
的大小可能非常大。 Is this possible operator<
(or std::less
) are not suitable for calculating offsets bases on address order. operator<
(或std::less
)不适合根据地址顺序计算偏移量。 Is it possible to use a custom allocator in this situation to resolve both issues? 在这种情况下是否可以使用自定义分配器来解决这两个问题?
As you note, std::vector doesn't save you anything (as a fixed-time lookup), because the size of the vector would need to be the size of the entire addressable memory space (or at least the heap). 如您所述,std :: vector不会为您节省任何费用(作为固定时间的查找),因为vector的大小必须是整个可寻址内存空间(或至少是堆)的大小。
I'd focus on the use-case: are you trying to find the address of the shared_ptr instance which contains a Foo, or something else? 我将重点放在用例上:您是否要查找包含Foo或其他内容的shared_ptr实例的地址? In the former case, I'd look into shared_from_this, for a possible trivial solution.
在前一种情况下,我将研究shared_from_this,以获得可能的简单解决方案。 In the latter case, you'd need to consider other design options (eg: if you're looking up the shared_ptr for an "equivalent" Foo, consider an ID method, and std::map lookup, or equivalent).
在后一种情况下,您需要考虑其他设计选项(例如:如果要在shared_ptr中查找“等效” Foo,请考虑使用ID方法和std :: map查找或等效方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.