gpt4 book ai didi

c++ - boost::container::small_vector 似乎没有就地分配

转载 作者:行者123 更新时间:2023-11-27 23:51:25 24 4
gpt4 key购买 nike

测试我对small_vector的理解,我尝试了下面的示例程序,我在其中将就地大小为 3 的 vector 模板化,并用 10 个元素填充 vector 。我希望前 3 个元素就地存储,最后 7 个元素存储在自由存储区的其他位置,但是当我观察内存布局时情况似乎并非如此:所有的项目似乎都是连续存储的,并且不在适当的位置,就像常规的 std::vector 一样。

我尝试了各种编译器(不同版本的 GCC 和 Clang)和不同的 Boost 版本,但这似乎没有什么不同。以下代码也没有更改:

  • 在自由存储上分配 vector 本身。
  • vec 本地前后用大尺寸本地包围,然后才用元素加载它。

对此有什么好的解释吗?

#include <iostream>
#include <boost/container/small_vector.hpp>

int main()
{
auto vec = boost::container::small_vector<int, 3> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

for (const auto& num : vec)
{
std::cout <<
"Index: " << num <<
" Distance from vec[0]: " << (long)&num - (long)&vec[0] <<
" Distance from vec: " << (long)&num - (long)&vec << "\n";
}
}

输出:

Index: 0 Distance from vec[0]: 0 Distance from vec: -140731961813152
Index: 1 Distance from vec[0]: 4 Distance from vec: -140731961813148
Index: 2 Distance from vec[0]: 8 Distance from vec: -140731961813144
Index: 3 Distance from vec[0]: 12 Distance from vec: -140731961813140
Index: 4 Distance from vec[0]: 16 Distance from vec: -140731961813136
Index: 5 Distance from vec[0]: 20 Distance from vec: -140731961813132
Index: 6 Distance from vec[0]: 24 Distance from vec: -140731961813128
Index: 7 Distance from vec[0]: 28 Distance from vec: -140731961813124
Index: 8 Distance from vec[0]: 32 Distance from vec: -140731961813120
Index: 9 Distance from vec[0]: 36 Distance from vec: -140731961813116
Index: 10 Distance from vec[0]: 40 Distance from vec: -140731961813112

参见: https://wandbox.org/permlink/zMGRxHlM96Riq9Ky

最佳答案

boost documentation ,

small_vector

small_vector is a vector-like container optimized for the case when it contains few elements. It contains some preallocated elements in-place, which allows it to avoid the use of dynamic storage allocation when the actual number of elements is below that preallocated threshold. small_vector is inspired by LLVM's SmallVector container. Unlike static_vector, small_vector's capacity can grow beyond the initial preallocated capacity.

small_vector is convertible to small_vector_base, a type that is independent from the preallocated element count, allowing client code that does not need to be templated on that N argument. small_vector inherits all vector's member functions so it supports all standard features like emplacement, stateful allocators, etc.

它说它的容量可以增长到超过初始的,但没有说当容量增长时将使用初始存储。

“vector ”事物通常被认为是连续的,它有很多好处。 (原始指针作为迭代器、超高速随机访问等。)放弃这些好处以减少小型动态内存使用(记住这是 "small"_vector )不是一个好的交易。

关于c++ - boost::container::small_vector 似乎没有就地分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46115267/

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