std::vector将它的元素连续存储在内存中而不是std::list.这样可以std::vector在遍历元素时提供更好的性能,因为在迭代a时,所有内容都整齐地打包在内存中std::list.
问题是大多数时候我将智能指针存储在向量中用于多态或用于与代码的其他部分共享这些对象.由于现在每个对象都是动态分配的,我假设它们最终位于不同的内存位置.这是否打败了使用a std::vector并基本上将其变成类似的东西的目的std::list?有什么办法可以解决这个问题吗?
No, it isn't pointless.
When iterating over a std::list of possibly smart pointers, you jump to nearly random points in memory on each iterator increment. When accessing, you again jump to a nearly random point in memory.
If you did the same iteration-access in a std::vector of possibly smart pointers, you would only jump to a nearly random point in memory once.
How can you make this less painful?
If you are using a std::shared_ptr, remember to do std::make_shared so the ref counter and the data are in the same allocation, reducing cache misses.
如果您只是将其用于多态性,理论上您可以存储类似 a boost::variant(或union各种类型的 a 以及说明类型是什么的内容),这允许多种类型的变量存在于同一地址(一个自然地,一次)。