Title
std::vector and std:string lack explicit shrink-to-fit operations
Status
cd1
Section
[vector.capacity][string.capacity]
Submitter
Beman Dawes

Created on 2007-10-31.00:00:00 last changed 172 months ago

Messages

Date: 2010-10-21.18:28:33

[ 850 has been added to deal with this issue with respect to deque. ]

Date: 2010-10-21.18:28:33

Proposed resolution:

To Class template basic_string [basic.string] synopsis, Class template vector [vector] synopsis, and Class vector<bool> [vector.bool] synopsis, add:

    
void shrink_to_fit();

To basic_string capacity [string.capacity] and vector capacity [vector.capacity], add:

void shrink_to_fit();

Remarks: shrink_to_fit is a non-binding request to reduce capacity() to size(). [Note: The request is non-binding to allow latitude for implementation-specific optimizations. — end note]

Date: 2007-10-31.00:00:00

A std::vector can be shrunk-to-fit via the swap idiom:

vector<int> v;
...
v.swap(vector<int>(v));  // shrink to fit

or:

vector<int>(v).swap(v);  // shrink to fit

or:

swap(v, vector<int>(v));  // shrink to fit

A non-binding request for shrink-to-fit can be made to a std::string via:

string s;
...
s.reserve(0);

Neither of these is at all obvious to beginners, and even some experienced C++ programmers are not aware that shrink-to-fit is trivially available.

Lack of explicit functions to perform these commonly requested operations makes vector and string less usable for non-experts. Because the idioms are somewhat obscure, code readability is impaired. It is also unfortunate that two similar vector-like containers use different syntax for the same operation.

The proposed resolution addresses these concerns. The proposed function takes no arguments to keep the solution simple and focused.

History
Date User Action Args
2010-10-21 18:28:33adminsetmessages: + msg3663
2010-10-21 18:28:33adminsetmessages: + msg3662
2007-10-31 00:00:00admincreate