Mat*_*atG 5 c++ return local-variables lifetime string-view
考虑这个片段:
#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';
}
Run Code Online (Sandbox Code Playgroud)
我天真地期待一些警告,to_stringview()比如返回本地临时的引用,但 g++ 和 clang 都没有说什么,所以这段代码看起来合法并且有效。
由于这会产生预期的警告:
const std::string& to_string() const noexcept
{
return "hey"s;
}
Run Code Online (Sandbox Code Playgroud)
我想知道通过哪种机制, 的生命周期"hello"与 的生命周期不同"hey"。
但 g++ 和 clang 都没有说什么,所以这段代码看起来合法并且有效。
你无法从前者推断出后者。许多非合法代码不会产生警告。
也就是说,字符串文字具有静态存储持续时间,因此它们的生命周期没有问题。to_stringview确实是合法的。
PS 字符串文字是字符数组。
我想知道“hello”的生命周期与“hey”的生命周期是通过哪种机制不同的。
这两个字符串文字的生命周期没有区别。但"hey"s不是字符串文字。它是一个“用户定义的”文字,用于创建该类的临时实例std::string。该临时对象没有静态存储持续时间。