I am dealing with a lot of strings in my program. These string data don’t change through out the whole life time after they being read into my program.
But since the C++ string reserves capacity, they waste a lot of space that won’t be used for sure. I tried to release those spaces, but it didn’t work.
The following is the simple code that I tried:
string temp = '1234567890123456'; string str; cout << str.capacity() << endl; str.reserve(16); cout << str.capacity() << endl; // capacity is 31 on my computer str += temp; cout << str.capacity() << endl; str.reserve(16); cout << str.capacity() << endl; // can't release. The capacity is still 31.
(The compiler is Visual C++)
How could I release it?
When you call
reserve, you’re making a request to change the capacity. Implementations will only guarantee that a number equal to or greater than this amount is reserved. Therefore, a request to shrink capacity may be safely ignored by a particular implementation.However, I encourage you to consider whether this isn’t premature optimization. Are you sure that you’re really making so many strings that it’s a memory bottleneck for you? Are you sure that it’s actually memory that’s the bottleneck?
From the documentation for
reserve: