As has been discussed previously, to force any standard container to release its heap memory you can just swap with (or assign to) an empty container.
But this does not appear to work for 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";
}
Output (Boost 1.76 on Linux x86_64):
4
142
142
I know I can call shrink_to_fit. But this is making some of my generic code messier than it should be, in my opinion.
Is this behavior deliberate? If so, why? If not, does it qualify as a bug?
To be super technical, there are no guarantees in the standard that the empty container won't initially have equally large capacity as the old one. As such, you technically cannot deduce from the capacity that allocation hadn't been freed.
Edit: As sehe's demo shows, there appears to not be an issue when using
std::swap(orboost::swap) in place of member swap.It shouldn't however be too bad to write a generic
shrink_if_has_capacity. I mean, the implementation of that template might be a few potentially messy lines, but its usage would be just as clean, and the intention even clearer than the swap.The documentation is extremely terse. There is no specification for the behaviour, nor a rationale. As such, the answer may be unknown except to the author.