Why can't the compiler optimize std :: string concat?

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.

+6
source share
1 answer

std::string includes dynamic storage allocation and, in most cases, an extremely complex implementation and therefore cannot be reduced to compilation-time semantics, regardless of how well the compiler has a constant summary of fine art.

However: If your string actually declared this way, why didn't you use the char array but choose string ? If you need to work with some strings to create others, there are still tools that can do this work with char arrays, especially since C ++ 11 introduced variable templates and constexpr . A future version of C ++ will hopefully also introduce std::string_literal to facilitate this.

+7
source

Source: https://habr.com/ru/post/977687/


All Articles