vector内存连续性的疑问
- C/C++ code
假设:vector<int> v 中已经有4个元素了。 这4个元素耗去了 16字节内存。此时 内存池中只有2个8字节的块。如果 有这样的一句代码:v.reseve(8); 意味着,v还需要16字节。由于16字节小于128,所以进入第二级配置器。问题:内存池会将这2个8字节的块 直接拨给vector吗?不会给vector,因为这2个8字节的块,直接拨给v, 但是 很可能 v以前的内存和 这2个8自己的内存 没有连续,那么是无法使用的。 那么stl如何判断 vector需要连续性内存呢??
[解决办法]
如果Vector当前容量不足,就会重新分配内存,把原来那部分数据复制到新的内存中
当然,我说的是STL的内存分配器
[解决办法]
额 vector的内存不可能说在原有的内存基础上再加一块进去。而是如果之前的内存不够,那么就重新分配一块更大的以容纳所有元素,原来持有的内存释放。就你这里来说 如果reseve(8)会引起内存的重新分配,那么他绝对是找一个8*4=32字节的内存块,然后将之前的4*4=16字节的内存块释放掉。
[解决办法]
- C/C++ code
void reserve(size_type _Count) { // determine new minimum length of allocated storage if (max_size() < _Count) _Xlen(); // result too long else if (capacity() < _Count) { // not enough room, reallocate pointer _Ptr = this->_Alval.allocate(_Count); _TRY_BEGIN _Umove(this->_Myfirst, this->_Mylast, _Ptr); _CATCH_ALL this->_Alval.deallocate(_Ptr, _Count); _RERAISE; _CATCH_END size_type _Size = size(); if (this->_Myfirst != 0) { // destroy and deallocate old array _Destroy(this->_Myfirst, this->_Mylast); this->_Alval.deallocate(this->_Myfirst, this->_Myend - this->_Myfirst); } this->_Orphan_all(); this->_Myend = _Ptr + _Count; this->_Mylast = _Ptr + _Size; this->_Myfirst = _Ptr; } }