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 that compiler(gcc 4.8.2/clang 3.5.0) optimize such code to
int main()
{
puts("ab");
return 0;
}
But I can not get such result, I try different options like "-Ofast", "-flto", "-static-libstdc++", but always see in disassembler output three functions call:
...
callq 0x4017e0 <_ZNSsC2EPKcRKSaIcE>
...
callq 0x401690 <_ZNSs6appendEPKc>
...
callq 0x401490 <_ZNSs4_Rep10_M_disposeERKSaIcE>
The first one is call to std::basic_string, std::allocator >::basic_string(char const*, std::allocator const&).
So are any compiler around, that can optmize such code to just puts("ab"); or at least to "std::string s("ab");"?
And if there are no such compiler, what make such optimization difficult to implement?
Update About real world usage. I see/saw many places in real code with such pattern:
std::string s = std::string(string_const1) + string_const2 + string_variable + string_const3;
And if performance is important, of course it is possible to rewrite such code in more optimal ways.
But modern compilers do great jobs to optimize code. And gcc, for example have __builtin functions for malloc/free/strcpy/strcat and so on. And if std::basic_string from libstdc++ from gcc use them this functions(malloc,free,strcpy,strcat) for part of implementation, why not predict the result of functions usage and give answer.
puts("ab");or equivalent. But compilers don't do it. I guess you would have to ask a compiler developer, but perhaps part of it has to do with respecting the wishes of the programmer. If they followed the as-if rule ultimately then there would be a lot of complaints; e.g. making a system call to write something on the screen, or do a sleep, has no observable behaviour as per the definition in C++14.