如前所述,要 强制任何标准容器释放其堆内存,您只需交换(或分配给)一个空容器即可。
但这似乎不适用于boost::small_vector
.
#include <boost/container/small_vector.hpp>
#include <iostream>
typedef boost::container::small_vector<int,4> Vec;
int main()
{
Vec v;
std::cout << v.capacity() << "\n";
for (int i = 0 ; i < 100 ; ++i)
v.push_back(i);
std::cout << v.capacity() << "\n";
Vec().swap(v);
// v = Vec(); // doesn't work either
std::cout << v.capacity() << "\n";
}
输出(Linux x86_64 上的 Boost 1.76):
4
142
142
我知道我可以打电话shrink_to_fit
。但在我看来,这使得我的一些通用代码比它应该的更混乱。
这种行为是故意的吗?如果是这样,为什么?如果不是,它是否有资格作为一个错误?