boost :: container :: small_vector似乎没有就地分配 [英] boost::container::small_vector doesn't seem to allocate in-place
问题描述
测试我对std::vector
一样,所有项目似乎都是连续且错位存储的.
To test my understanding of small_vector
, I tried the sample program below, where I template the vector with an in-place size of 3 and populate the vector with 10 elements. I'd expect the first 3 elements to be stored in-place and the last 7 elements to be stored out-of-place on the free-store, but that doesn't seem to be the case when I observe the memory layout: all of the items seem to be stored contiguously and out-of-place, as with a regular std::vector
.
我尝试了各种编译器(GCC和Clang的不同版本)和不同的Boost版本,但这似乎没有什么不同.以下代码也没有更改:
I tried various compilers (different versions of GCC and Clang) and different Boost versions, but that doesn't seem to make a difference. Neither do the following code changes:
- 在免费商店中分配媒介本身.
- 将
vec
局部变量前后用大尺寸局部变量包围,然后才将其装入元素.
- Allocating the vector itself on the free-store.
- Surrounding the
vec
local with large-size locals before and after, and only then loading it up with elements.
对此有什么好的解释吗?
Is there any good explanation for this?
#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