【问题标题】:How returning a string_view of a local literal works返回本地文字的 string_view 如何工作
【发布时间】:2021-10-23 20:38:07
【问题描述】:

考虑一下snippet

#include <iostream>
#include <string>
#include <string_view>
using namespace std::literals;

class A
{
 public:
    std::string to_string() const noexcept
       {
        return "hey"; // "hey"s
       }

    std::string_view to_stringview() const noexcept
       {
        return "hello"; // "hello"sv
       }
};

int main()
{
    A a;
    std::cout << "The class says: " << a.to_string() << '\n';
    std::cout << "The class says: " << a.to_stringview() << '\n';
}

我天真地期待to_stringview() 中出现一些警告,例如返回对本地临时对象的引用,但是 g++ 和 clang 都什么也没说,所以这段代码看起来合法且有效。

因为这会产生预期的警告:

    const std::string& to_string() const noexcept
       {
        return "hey"s;
       }

我想知道"hello" 的生命周期与"hey" 的生命周期通过哪种机制不同。

【问题讨论】:

  • 好吧,如果你尝试返回const std::string_view&amp;,你会得到the same warning
  • 您似乎没有将同类与同类进行比较。您的最后一个 sn-p (显式)返回一个 const 引用,但前面的 sn-p 中的等效项(使用“hey”而不是“hello”)返回一个 string 对象 按值,构造从字面上看。对 string_view 函数使用按引用返回有同样的问题,而且解释起来有点棘手......这就是你的意思吗?
  • @AdrianMole 嗨,阿德里安,string_view 已经是一个参考,因此与std::string&amp; 具有可比性(有点)
  • 问题是,返回的string 按值 将制作自己的源数据副本;但是,string_view 只会复制源数据的地址。但是,正如答案中所解释的,字符串文字无论如何都是静态的。

标签: c++ return lifetime local-variables string-view


【解决方案1】:

但是 g++ 和 clang 都什么也没说,所以这段代码看起来合法且有效。

你不能从前者推断出后者。许多不合法的代码不会产生警告。

也就是说,字符串文字具有静态存储持续时间,因此它们的生命周期没有问题。 to_stringview 确实是合法的。

附:字符串字面量是 char 数组。

我想知道“hello”的生命周期与“hey”的生命周期是通过哪种机制不同的。

这两个字符串文字的生命周期没有区别。但"hey"s 不是字符串文字。它是一个“用户定义”字面量,用于创建类std::string 的临时实例。该临时对象没有静态存储持续时间。

【讨论】:

  • 所以我想我明白了:std::string 文字不能有静态存储。
  • @MatG 是的。字符串字面量(不是用户定义的 std::string 字面量)非常特殊。
猜你喜欢
  • 2021-12-09
  • 2018-03-04
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多