vector<Person> p;
//此处Person为类名,仅此一行代码,会调用p(即vector本身)的构造函数,此时p是空的,其元素的构造函数并未被调用
//
p.reserve(3);
//reserve函数预留空间,一下为源码
template<typename _Tp, typename _Alloc>
void
vector<_Tp, _Alloc>::
reserve(size_type __n)
{
if (__n > this->max_size())
__throw_length_error(__N("vector::reserve"));
if (this->capacity() < __n)
{
const size_type __old_size = size();
pointer __tmp = _M_allocate_and_copy(__n,
_GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(this->_M_impl._M_start),
_GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(this->_M_impl._M_finish));
std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish,
_M_get_Tp_allocator());
_M_deallocate(this->_M_impl._M_start,
this->_M_impl._M_end_of_storage
- this->_M_impl._M_start);
this->_M_impl._M_start = __tmp;
this->_M_impl._M_finish = __tmp + __old_size;
this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n;
}
}
//可以看出,reserve并未构造出元素,仅仅是预留空间,其后要通过push_back加元素,好处是不用加一次就整体搬一次家;
//
p.resize(3);
//resize用于重新划定空间,以下为源码
void
resize(size_type __new_size)
{
if (__new_size > size())
_M_default_append(__new_size - size());
else if (__new_size < size())
_M_erase_at_end(this->_M_impl._M_start + __new_size);
}
//可以看出,resize是增添或者删除了元素的
//当增添元素时,注意,调用的是元素的默认构造函数,假如是 类类型+特殊需求构造了个带参数的构造函数,导致 默认构造函数失效 ,使程序错误;
//此时要将这些都加上,形成函数重载;