说明
在STL中 vector和string 是比较特殊的,clear()之后是不会释放内存空间的,也就是size()会清零,但capacity()不会改变,需要手动去释放,说明 clear() 没有释放内存。
想释放空间的话,除了swap一个空string外,c++11里新加入的的std::basic_string::shrink_to_fit 也可以。代码
注意string的swap清空方法为:string().swap(str);vector的swap清空方法为:nums.swap(vector<int>());
#include <iostream> #include <string> int main() { std::string s; std::cout << "Default-constructed capacity is " << s.capacity() << " and size is " << s.size() << '\n'; for (int i = 0; i < 42; i++) s.append(" 42 "); std::cout << "Capacity after a couple of appends is " << s.capacity() << " and size is " << s.size() << '\n'; s.clear(); std::cout << "Capacity after clear() is " << s.capacity() << " and size is " << s.size() << '\n'; s.shrink_to_fit(); std::cout << "Capacity after shrink_to_fit() is " << s.capacity() << " and size is " << s.size() << '\n'; for (int i = 0; i < 42; i++) s.append(" 42 "); std::cout << "Capacity after a couple of appends is " << s.capacity() << " and size is " << s.size() << '\n'; string().swap(s); std::cout << "Capacity after swap() is " << s.capacity() << " and size is " << s.size() << '\n'; }
输出为:Default-constructed capacity is 15 and size is 0
Capacity after a couple of appends is 235 and size is 168
Capacity after clear() is 235 and size is 0
Capacity after shrink_to_fit() is 15 and size is 0
Capacity after a couple of appends is 235 and size is 168
Capacity after swap() is 15 and size is 0
————————————————版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_41687938/article/details/117731243C++ string清空并释放内存空间的两种方法(shrink_to_fit()、swap())_c++ string 释放-CSDN博客
12-01
238
01-10
333
03-15
1118
07-15
1306