So, I was reading about using enum
as part of the new C++2a standards here and came across the following code:
enum class rgba_color_channel { red, green, blue, alpha};
std::string_view to_string(rgba_color_channel channel) {
switch (my_channel) {
using enum rgba_color_channel;
case red: return "red";
case green: return "green";
case blue: return "blue";
case alpha: return "alpha";
}
}
This got me to wonder how returning a std::string_view works? To my mind "red", "green", ... are temporary variables and the thus should not work, so I wrote some test code:
std::string_view to_red() {
return "red";
}
std::string_view to_green() {
const char* green{ "green" };
return green;
}
std::string_view to_blue() {
std::string blue{ "blue" };
return blue;
}
std::string_view to_alpha() {
std::string alpha{ "alpha" };
return std::string_view(alpha);
}
int main()
{
std::cout << "red: " << to_red() << "\n";
std::cout << "green: " << to_green() << "\n";
std::cout << "blue: " << to_blue() << "\n";
std::cout << "alpha: " << to_alpha() << "\n";
}
Output:
red: red
green: green
blue: ╠╠╠╠
alpha: ╠╠╠╠╠
Blue and alpha behaved as I expected (undefined behavior), however red and green did not. So, my question is why does const char*
seem to work? Or is this just a msvc manifestation of undefined behavior?