【问题标题】:Returning a std::string_view to a const char * [duplicate]将 std::string_view 返回到 const char * [重复]
【发布时间】:2020-02-09 20:41:40
【问题描述】:

所以,我在阅读 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 是如何工作的?在我看来“红色”、“绿色”、... 是临时变量,因此不应该工作,所以我写了一些测试代码:

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 表现?

【问题讨论】:

    标签: c++ string-view


    【解决方案1】:

    在我看来,“红色”、“绿色”……是临时变量,因此不应该工作

    没有。 String literalsstatic storage duration 并因此在程序的生命周期中存在于内存中。

    返回 std::string_view 的工作原理是什么?

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

    我的问题是为什么 const char* 似乎有效?

    因为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");
    }
    

    或者这只是未定义行为的 msvc 表现?

    没有。

    【讨论】:

    • static storage duration 是我不明白的。谢谢
    • 如果您查看程序的目标代码,您会发现其中嵌入的字符串文字(通常在特殊文本部分中)。由于这些是加载到内存中以便执行的程序的一部分,因此它们具有可以使用的固定地址。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2015-11-07
    • 2022-01-06
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多