Is there a way to pre-specify a specific string buffer size for the underlying buffer
to which repeated concatenations are going to be made in a loop with the purpose of
eliminating time wasting re-allocations and block movements of characters from one
buffer to another? I have tried the string::reserve() member but in my trials at
least it appears useless; the first assignment of a string to an object to which
it was applied results in the string::capacity() being reset to the approximate length
of the string assigned; whatever the original string::reserve() was set to is lost.
Perhaps some kind of 'lock' type capacity, but I don't see anything like that. Here
is an example program showing my problem, as well as its output which shows that my
initial 'reserve()' of 256 bytes is being completely ignored and lost...
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
string s1[]={"Zero ","One ","Two ","Three ","Four ","Five ","Six "};
string s2;
s2.reserve(256); //Set buffer to 256???
printf("s2.capacity() = %d\n\n\n",s2.capacity());
printf("i\ts1.c_str()\n");
printf("==================\n");
for(unsigned i=0; i<sizeof(s1)/sizeof(s1[0]); i++)
printf("%d\t%s\n",i,s1[i].c_str());
printf("\n\n");
printf("i\ts2.capacity()\ts2.size()\ts2.c_str()\n");
printf("=========================================================================\n");
for(unsigned i=0; i<sizeof(s1)/sizeof(s1[0]); i++)
{
s2=s2+s1[i]; //reserve doesn't maintain 256???
printf("%d\t%d\t\t%d\t\t%s\n",i,s2.capacity(),s2.size(),s2.c_str());
}
getchar();
return 0;
}
s2.capacity() = 256
i s1.c_str()
==================
0 Zero
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
i s2.capacity() s2.size() s2.c_str()
=========================================================================
0 5 5 Zero
1 10 9 Zero One
2 20 13 Zero One Two
3 19 19 Zero One Two Three
4 38 24 Zero One Two Three Four
5 29 29 Zero One Two Three Four Five
6 58 33 Zero One Two Three Four Five Six
As can be seen above, the very first line of the program (after variable declarations)
does a string::reserve() on s2 for 256 bytes. Immediately after that an output
statement shows that the capacity is indeed 256. However, the string array s1 is
concatenated into s2 in the bottom for loop, and prior reserve settings appear to be
completely ignored/lost as the output clearly shows.
I have to admit I've never used the Standard C++ Library String Class (I have my own
which seems to be a bit more efficient), so I'm struggling here. Help would be greatly
appreciated.