reserve指容量,resize会调用reserve,之外还会创建对象。
reserve的操作全是针对内存的,当capacity小于要指定的count时,reserve会reallocate创建内存,但是不会生成对象。
resize的操作更关心的操作对象。
打个比方:正在建造的一辆公交车,车里面可以设置40个座椅(reserve(40);),这是它的容量,但并不是说它里面就有了40个座椅,只能说明这部车内部空间大小可以放得下40张座椅而已。而车里面安装了40个座椅(resize(40);),这个时候车里面才真正有了40个座椅,这些座椅就可以使用了。 本例转自该链接
reserve源码:
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; } }
void resize(size_type _Newsize) { // determine new length, padding with _Ty() elements as needed if (_Newsize < size()) erase(begin() + _Newsize, end()); else if (size() < _Newsize) { // pad as needed _Reserve(_Newsize - size()); _Uninitialized_default_fill_n(this->_Mylast, _Newsize - size(), (_Ty *)0, this->_Alval); this->_Mylast += _Newsize - size(); } } void resize(size_type _Newsize, _Ty _Val) { // determine new length, padding with _Val elements as needed if (size() < _Newsize) _Insert_n(end(), _Newsize - size(), _Val); else if (_Newsize < size()) erase(begin() + _Newsize, end()); }