将 std::string_view 返回给 const char *

Returning a std::string_view to a const char *

所以,我在阅读有关 using enum 作为新 C++2a 标准 here 的一部分的内容时,遇到了以下代码:

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";
  }
}

这让我想知道返回 std::string_view 是如何工作的?在我看来 "red", "green", ... 是临时变量,因此不应该工作,所以我写了一些测试代码:

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";
}

输出:

red: red
green: green
blue: ╠╠╠╠
alpha: ╠╠╠╠╠

蓝色和 alpha 的行为符合我的预期(未定义行为),但红色和绿色没有。所以,我的问题是为什么 const char* 似乎有效?或者这只是未定义行为的 msvc 表现形式?

To my mind "red", "green", ... are temporary variables and the thus should not work

没有。 String literals have static storage duration 因此在程序的整个生命周期中都存在于内存中。

how returning a std::string_view works?

嗯,它从字符串文字构造 string_viewstring_view 存储的是指向字符串字面量的指针,所以只要字符串字面量有效,它就有效。由于字符串文字在程序的生命周期内有效,因此 string_view 也有效。

my question is why does const char* seem to work?

因为const char*指针指向字符串文字。

std::string_view func() { 
    return "this is a string literal";
    const char *also_a_string_literal = "another string literal";
    const char not_a_string_literal_on_stack[] = "text";
    std::string constructed_using_dynamic_allocation("or not, it depends");
}

Or is this just a msvc manifestation of undefined behavior?

没有