Can we rely on the reduce-capacity trick?

I’ve always been taught that there is no guaranteed standard way to lower the capacity. All methods have been (and still are) implementation defined.

§ 23.2.1\8 says:

The expression a.swap(b), for containers a and b of a standard
container type other than array, shall exchange the values of a and b
without invoking any move, copy, or swap operations on the individual
container elements…

This guarantees that the internal pointers of vectors must be swapped.
However, I cannot find anything that guarantee on the capacity of a newly created vector.

§ 21.4.2\1 says that one of the basic_string default constructor’s post conditions is that capacity() returns an unspecified value.
§ 21.4.2\3 says that one of the basic_string copy constructor’s post conditions is that capacity() returns a value at least as big as size().
§ 21.4.6.8\2 says that string::swap runs in constant time, which (effectively) requires that the internal pointers are swapped.

As far as I can tell, a conforming implementation could have string::max_size() { return 4;}, and swapping all internals from one buffer to another would therefore be constant time. (vector can’t do that though)

Obviously, take this all with a grain of salt. I’m quoting from the C++ draft from Feb28,’11, and I can’t find specifications for the vector’s copy constructor. Also, not finding evidence for is not the same as finding evidence against.

Leave a Comment