I try such simple code:
#include <cstdio> #include <string> int main() { const std::string s = std::string("a") + "b"; puts(s.c_str()); return 0; }
I expect the compiler (gcc 4.8.2 / clang 3.5.0) to optimize such code for
int main() { puts("ab"); return 0; }
But I canβt get such a result, I try different options, such as "-Ofast", "-flto", "-static-libstd ++", but I always see three call functions in the output of the disassembler:
... callq 0x4017e0 <_ZNSsC2EPKcRKSaIcE> ... callq 0x401690 <_ZNSs6appendEPKc> ... callq 0x401490 <_ZNSs4_Rep10_M_disposeERKSaIcE>
The first call is std :: basic_string, std :: allocator> :: basic_string (char const *, std :: allocator const &).
So any compiler that can select such code just puts ("ab"); or at least until "std :: string s (" ab ");"?
And if there is no such compiler, what is difficult to make such optimization?
Update on real world use. I see / saw many places in real code with this pattern:
std::string s = std::string(string_const1) + string_const2 + string_variable + string_const3;
And if performance is important, then of course you can rewrite such code in a more optimal way.
But modern compilers do a great job of code optimization. And gcc, for example, have __builtin functions for malloc / free / strcpy / strcat, etc. And if std :: basic_string from libstdc ++ from gcc uses these functions (malloc, free, strcpy, strcat) for the implementation part, why not predict the result of using the functions and give an answer.