anon_user anon_user - 1 year ago 126
C++ Question

C++ How to preserve string capacity when copying

So I have this string that has changing space in the end. For example (this isn't my actual code, just for example purposes):

std::string myString = "hey!";
myString.reserve(myString.size() + MAX_BUFFER_SPACE);

// ( ... making buffer and stuff ... )

size_t l = myString.size();
if (bufferLen>=MAX_BUFFER_SPACE) throw;

// ( ... using this new string ... )

myString.resize(l); // <-- this is my problem!

Now, the reserved space doesn't stay. I mainly do C, so I don't actually have problem with resorting to char*:s. But please do tell if there's functionality for this in the string library.


The problem is not that! However, I'm able to reproduce my problem with this example:

#include <string>
#include <vector>
using namespace std;

#define MAX_BUFFER 30

int main(int argc, char **argv) {

vector<string> myVec = { "hey","asd","haha" };
vector<string> clone;

for (int i = myVec.size(); i--;) {
myVec[i].reserve(myVec[i].size() + MAX_BUFFER);

return 0;

Add a breakpoint before return 0; . Now, inspect strings that are in myVec and clone. Their capacity is not the same!

Answer Source

The capacity is not requested to be copied to be same when std::string being copied.

$ basic_string constructors and assignment operators [string.cons]:

Table 49 — basic_string(const basic_string&) effects
Element   Value
data()    points at the first element of an allocated copy of the array whose first element is pointed at by
size()    str.size()
capacity()    a value at least as large as size()

The only guarantee is the capacity of the string will be at least as large as its size after copying.

It means you have to do this by yourself:

for (int i = myVec.size(); i--;) {
    myVec[i].reserve(myVec[i].size() + MAX_BUFFER);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download