Simple question: If I have a string and I want to add to it head and tail strings (one in the beginning and the other at the end), what would be the best way to do it? Something like this:
std::string tmpstr("some string here");
std::string head("head");
std::string tail("tail");
tmpstr = head + tmpstr + tail;
Is there any better way to do it?
Thanks in advance.
operator+()is always a temporary (rvalue). Absent of C++1x rvalue references, if you don't need to further modify the result, you can probably optimize away one superflous copying by storing the result in a const reference, instead of copying it into an object:const T& result = a + b;This will bind the temporary to the refrence and extend its lifetime accordingly. While your compiler might optimize out this one copy anyway (unlikely with strings, I'd say), so you might not gain anything, using this technique won't hurt performance.