问题
I can see it listed as one of the modern C++ idioms, but what it is exactly?
Is it just a type of copy elision?
回答1:
You might know that std::strlen loops over the whole string. This can be inefficient in some cases, as it means that the CPU has to start counting characters, which reduces cache locality for other stuff.
But in most cases, the compiler is able to optimize std::strlen
and count the number of characters of the string itself instead of making the resulting program do it. This is sometimes called strlen elision (because it elides the call to strlen).
A simple example of std::strlen
would simply get optimized completely.
#include <cstring>
int main() {
return std::strlen("hi");
}
Under -O3
the resulting assembly is
main: # @main
mov eax, 2
ret
Even under -O0 no loop is generated!
Now this is a rather simple example, but it works even for a bit more complicated usages of std::strlen
.
#include <cstring>
int main(int argc, char**) {
const char *string;
if (argc == 1)
string = "hello";
else if (argc == 2)
string = "world";
else if (argc == 3)
string = "!";
return std::strlen(string);
}
Here the strings are completely optimized away, as well as the std::strlen
call.
回答2:
With all due respect to Rakete, it seems self-evident to me that if the compiler understands the semantics of strlen, and if the string in question is known at compile time, then the compiler can just emit a constant rather than evaluating the length of the string (by whatever means) at runtime. That's all that is happening here. Trust Microsoft's marketing department to hype-up such a simple feature.
What interests me about all this is the increasing trend for (optimising) compilers to treat commonly used runtime library functions as intrinsics and emit better code for them when it can. This has been going on for a while - memcpy and memset are obvious examples - but I was playing around in Godbolt's Compiler Explorer recently and was amazed to see gcc replace this:
printf (" ");
with this:
putchar (' ');
Shocked? Me too, and I'm not sure I like it. I might have a custom printf that does something special and this sort of trickery would come as a rude surprise. Seems to me a big risk (by the compiler writers) for such a small gain.
来源:https://stackoverflow.com/questions/49714284/what-is-strlen-elision