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.
std::string
involves dynamic allocation of storage and, in most cases, an extremely complex implementation and can therefore not be reduced to compile-time semantics, no matter how well the compiler has constant folding down to a fine art.
However: If your string
is actually declared like this why didn't you use a char
array in the first place but chose string
?
If you need to work with some strings to produce others, there are still tools that can do that job with char
arrays, especially since C++11 introduced variadic templates and constexpr
. A future version of C++ will hopefully also introduce std::string_literal
to further ease that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With