我的问题是由 stackoverflow 上的这个答案 https://stackoverflow.com/a/48082010/5360439 引起的。引用,
Q: How you convert a
std::string_view
to aconst char*
?A: Simply do a
std::string(string_view_object).c_str()
to get a guaranteed null-terminated temporary copy (and clean it up at the end of the line).
不幸的是,它构造了一个新的string
。我想知道是否可以简单地做,
static_cast<string>(string_view_object).c_str()
现在,我的问题是:
这会构造一个新字符串吗?
是否保证返回以空字符结尾的字符序列?
我有一小段代码用于演示。它似乎工作正常。 (参见魔杖盒 results )
#include <string>
#include <iostream>
#include <string_view>
#include <cstring>
int main()
{
std::string str{"0123456789"};
std::string_view sv(str.c_str(), 5);
std::cout << sv << std::endl;
std::cout << static_cast<std::string>(sv) << std::endl;
std::cout << strlen(static_cast<std::string>(sv).c_str()) << std::endl;
}
最佳答案
static_cast<std::string>(sv)
正在调用std::string::string
期望任何可转换为 std::string_view
的类型的构造函数(more details)。因此,是的,它仍在创建一个全新的 std::string
对象,这反过来又保证了一个以空字符结尾的字符序列。
关于c++ - 将 string_view 静态转换为字符串是否合法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54211456/