I got that sample source:
std::string tmp1;
std::string tmp2 = "Test";
while(1)
{
tmp1 += tmp2;
}
We see that tmp1 gets the content of tmp2 and each loop it adds “Test” at the end of the string. I know that this should be similar to strcat(), but strcat is a C function and it has got C function realloc()
How do std::string implements concatenation of strings?
Does it use some kind of reallocation of memory? If yes how do I reallocate in C++?
First off,
strcat()doesn’t allocate any memory! If you provide a too small buffer tostrcat()you’ll get a buffer overrun, not a reallocation.The
std::stringclass internally manages memory. It will reallocate memory using a suitable sequence of using new and delete operators. The way it is specified it will overallocate memory and not allocate new memory on each string addition.If you need to use variable sized amounts of memory, you are probably best off to use
std::vector<T>for a suitable typeT. This class takes care of allocating and releasing memory. You just tell it how many elements you need. Under the hood it is also using combinations of new and delete operators (well, actually an allocator object) to maintain memory. There is no direct support for something like C’srealloc().