在某些实现中,调整大小几乎肯定会首先调用reserve.最近实现了std :: vector的变体,下面是
std::vector::reserve的精简和注释版本……(这些评论是为了OP的理解)……实际上,大多数STL实现将比这稍微复杂一些(对于调试目的);但它的概念基本相同.
template
void Vector::reserve(SizeType sz){
//if only the new size is greater than current capacity
if(sz > m_capacity){
//allocate the new size
T* data = static_cast(SFAllocator::allocate(sz));
//move all previous data
for(SizeType i=0; i < m_size; i++){
new(data+i) T(std::move(m_data[i])); //! TODO: move if only noexcept;
//call the destructor on the moved item
call_destructor(m_data[i]);
}
//deallocate formerly used memory
SFAllocator::deallocate(m_data);
//reassign the capacity to the new capacity
m_capacity = sz;
m_data = data; //reassign the data pointer
//size remains the same
}
以下是std::vector::resize的精简和注释版本.正如您在下面看到的那样,调整大小会先调用预留.
template
void Vector::resize(SizeType sz){
// resize it to fit at least fit to "sz"
reserve(sz);
//if higher size is requested
if(sz > m_size)
//default construct the remainder of the new uninitialized memory
for(SizeType i= m_size; i < sz; i++)
new(m_data+i) T{}
//if the container size is to get smaller
else
for(SizeType i=sz; i
call_destructor(m_data[i]); //delete the elements at indexes above "sz"
m_size = sz; //change container size.
}