Source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <vector> #include <iostream>
void func(std::vector<unsigned long> &datas) { for (auto &data : datas) { data++; } }
int main() { std::vector<unsigned long> v{01,02, 2, 3, 4,5,6}; func(v); v.push_back(16); v.push_back(32); v.push_back(256); func(v); size_t size = v.size(); std::cout << size << std::endl; size = v.capacity(); std::cout << size << std::endl; return 0; }
|
Debug
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| > g++ -O1 vector.cpp -o vector
> gdb vector
(gdb) br func (gdb) run
(gdb) x /4gx $rdi 0x7fffffffda50: 0x000055555556aeb0 0x000055555556aee8 0x7fffffffda60: 0x000055555556aee8 0x0000555555555499
(gdb) x /8gx 0x000055555556aeb0 0x55555556aeb0: 0x0000000000000001 0x0000000000000002 0x55555556aec0: 0x0000000000000002 0x0000000000000003 0x55555556aed0: 0x0000000000000004 0x0000000000000005 0x55555556aee0: 0x0000000000000006 0x000000000000f121
(gdb) c (gdb) x /4gx $rdi 0x7fffffffda50: 0x000055555556aef0 0x000055555556af40 0x7fffffffda60: 0x000055555556af60 0x0000555555555499 (gdb) x /12gx 0x000055555556aef0 0x55555556aef0: 0x0000000000000002 0x0000000000000003 0x55555556af00: 0x0000000000000003 0x0000000000000004 0x55555556af10: 0x0000000000000005 0x0000000000000006 0x55555556af20: 0x0000000000000007 0x0000000000000010 0x55555556af30: 0x0000000000000020 0x0000000000000100
|
Layout
从调试的结果来看, vector 对象中包含三个指针: begin, end, capacity.
begin: 分配内存空间的首地址
end: 有效数据的截止地址
capacity: 分配内存空间的结束地址