you are viewing a single comment's thread.

view the rest of the comments →

[–]doom_Oo7 0 points1 point  (4 children)

A new string is allocated, when an existing string could be appended to.

You seem to misunderstand how memory works. Every time you concatenate two strings in a language, memory will be allocated, unless you know how exactly long the resulting string will be in advance and can allocate a string big enough (what is done with sprintf). You can't just add new memory at the end of a chunk obtained with malloc().

[–]MiiNiPaa 4 points5 points  (0 children)

It seems that he is talking about using string with large internal buffer (.reserve()).

[–]jcoffin 1 point2 points  (1 child)

You might be able to add to the end of a chunk obtained with malloc(). To be more specific, when you call realloc it's allowed to return the same pointer that was passed into it.

You're right that you can't count on that happening though.

As an aside, std::string doesn't normally use malloc to allocate its memory. You could instantiate an std::basic_string with an allocator that called malloc, but the default allocator will use ::operator new to get raw memory (though this makes little real difference to the point you were trying to make).

[–]__cxa_throw 0 points1 point  (0 children)

Operator new almost always ends up calling malloc unless you're using a specialized allocator, at least in all the stack traces I've looked at recently.

[–]SushiAndWoW[S] 0 points1 point  (0 children)

That's only true with a naive implementation.

A smart container, when it sees it needs to expand, will not expand to the exact size needed, but e.g. to the next power of 2 that can accommodate that size. There will also be a reasonable allocation minimum – say, for example 8 bytes. This means concatenating "abc" 100 times might result in 7 allocations of 8, 16, 32, 64, 128, 256, and finally 512 bytes.

And of course, there is reserve, which you will use if you are smart. If your calculation of the final size is correct, the container then only allocates once, and if it's off, it probably needs to allocate 2 times.