Reputation: 43
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!
Upvotes: 0
Views: 475
Reputation: 172864
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());
}
Upvotes: 4
Reputation: 61
myString.resize(l)
will not change the string's capacity, except when l
is large then the string's size. Just call myString.capacity()
and see for yourself.
Upvotes: 0
Reputation: 981
Yes, string class has a member function String resize member funtion..
Upvotes: 0