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