C++ 中的向量如何使用内存?

How does vectors in C++ use memory?

#include <iostream>
#include <vector>

int main(int argc, char const *argv[])
{
    std::vector<int> a(32768, 0);
    std::cout << "Size " << sizeof a << "\nCapacity " << a.capacity() << "\nElements " << a.size();
    return 0;
}

对于这个程序,我得到的输出是:

Size 24
Capacity 32768
Elements 32768

我使用 valgrind 计算了堆使用情况:

132096 字节

即(32768 x 4 字节)+ 24 字节

我对向量 a

如何使用这 24 个字节感兴趣

如 Kamil 在评论中所述,std::vector 在内部跟踪三个指针。一个指向开始的指针,一个指向结束的指针,一个指向已分配内存的末尾(参见 ). Now, the size of a pointer should be 8 bytes on any 64-bit C/C++ compiler so, 3 * 8 bytes = 24 bytes (see wiki)。