如果我有以下两个函数:
std::string tolower(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return static_cast<unsigned char>(std::tolower(static_cast<unsigned char>(c))); });
return s;
}
std::string_view tolower2(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return static_cast<unsigned char>(std::tolower(static_cast<unsigned char>(c))); });
return s;
}
唯一的区别是它们的返回值。
这些函数的结果是:
// returns "test" - expected
std::cout << tolower("TeSt") << std::endl;
// returns " est" - not expected
std::cout << tolower2("TeSt") << std::endl;
为什么会有差异?
最佳答案
因为在第一个示例中,您只是返回并使用了一个字符串(既安全又安全)。
在第二个示例中,您可能(见下文)返回一个不再存在的本地字符串的 View ,因此该 View “悬空”并且您的程序具有未定义的行为。
显然,在您的情况下,函数返回机制和/或字符串销毁机制的某些部分已经覆盖了曾经是字符串缓冲区的第一个字符。
[expr.call/7]:
[..] It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression. [..]
关于c++ - 返回 `std::string_view` 不包括第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675726/