Search code examples
c++stringinsertresizecapacity

C++ How to preserve string capacity when copying


EDIT (original post in edit history)

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);
        clone.push_back(myVec[i]);
    }

    return 0;
}

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


Solution

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

    $21.3.1.2/2 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 str.data()
    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);
        clone.push_back(myVec[i]);
        clone.back().reserve(myVec[i].capacity());
    }