简体   繁体   中英

C++ string concatenation performance

If i have for example this code :

string x = "xyz"

x=x+"qwe";

How does the previous operation work , does it allocate a new string with double the size of x and then it copies the old elements and then the new elements ?

Without compiler optimisations, yes. x+"qwe" is an expression which could be used in any place, not just on the right side of an assignment of x, so it will create a new std::string object with the length of 6. In a second step, x is assigned the value of this new std::string object and the new string object is discarded. A smart compiler with optimisations enabled might be clever enough to eliminate the creation of the temporary object in the first place, but it is not guaranteed of course.

If you want to enforce this, you can write instead:

x += "qwe";

which prevents the creation of any temporary object. Still the string object might need to allocate memory, if the new size exceeds its capacity. You can check this by looking at x.capacity(), and you can pre-reserve memory using x.reserve(), if you are concerned about real time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM