I am using a combination of C and C++ code in my application.
I want to print out if a boolean flag is true or false as below, by using a ternary operator to determine the string to print.
If I use a const char*, doesn't the compiler more than likely store these string literals "Yes" and "No" in some read-only memory before the program starts.
If I use std::string, when the string goes out of scope, it will be destroyed? But I guess the complier still needs to store the string literals "Yes" and "No" somewhere anyways? I'm not sure.
bool isSet = false;
// More code
//std::string isSetStr = isSet ? "Yes" : "No";
const char* isSetStr = isSet ? "Yes" : "No";
//printf ( "Flag is set ? : %s\n", isSetStr.c_str());
printf ( "Flag is set ? : %s\n", isSetStr);
You can test it with godbolt. The former (using
const char*) gives this:The latter (using std::string) gives this:
Using
std::string_viewsuch as:gives:
So to sum up, both
const char*andstring_viewgives optimal code.string_viewis a bit more code to type compared toconst char*.std::stringis made to manipulate string content, so it's overkill here and leads to less efficient code.Another remark with
string_view: It does not guarantee that the string is NUL terminated. In this case, it is, since it's built from a NUL terminated static string. For a genericstring_viewusage withprintf, useprintf("%.*s", str.length(), str.data());EDIT: By disabling exception handling, you can reduce
std::stringversion to:which is still a lot more than the
string_view's version. Remark that the compiler was smart enough to remove the memory allocation on the heap here, but it's still forced to compute the string's length (even if printf will also compute it itself).