测试
编译这样一段代码
int main()
{
std::vector<size_t> vec{1,2,3};
std::cout << vec.data() << std::endl;
std::cout << *vec.data() << std::endl;
std::cout << vec.size() << std::endl;
vec.clear();
std::cout << vec.data() << std::endl;
std::cout << *vec.data() << std::endl;
std::cout << vec.size() << std::endl;
return 0;
}
输出结果为
Program returned: 0
0x1b57eb0
1
3
0x1b57eb0
1
0
可以发现clear()
发生后首地址和所指元素值并为发生改变,仅size()
归零。
解释
Clear content
Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function.
规避
使用swap
方法则可以确保reallocation发生。
vector<T>().swap(x); // clear x reallocating