Reputation: 131435
Consider the following code:
#include <string>
#include <cstring>
size_t foo(const char* cptr)
{
if (cptr == nullptr) { return 0; }
return strlen(cptr);
}
size_t bar()
{
static const char* cptr { "Hello world" };
return std::string{cptr}.length();
}
size_t baz(const char* cptr)
{
if (cptr == nullptr) { return 0; }
return std::string{cptr}.length();
}
Using GodBolt, we can see that GCC 8.1 and Clang++ 6.0 can optimize-out the std::string
in both bar()
, but not in baz()
. In baz()
, while the compiler can't return a fixed value, it can definitely just run the code for checking string length, without constructing anything, or at least without completing the construction - i.e. behave similarly to foo()
. Why does it fully construct the string?
Upvotes: 1
Views: 252
Reputation: 180415
In baz
the compiler has no idea what cptr
points to so it has to construct a string to get it's size.
In bar
the compiler knows what cptr
points to "Hello world"
so it can replace the string creation and the call to size
with the size of the string.
Upvotes: 2