c++ - 将 string_view 静态转换为字符串是否合法

标签 c++ static-cast string-view

我的问题是由 stackoverflow 上的这个答案 https://stackoverflow.com/a/48082010/5360439 引起的。引用,

Q: How you convert a std::string_view to a const 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()

现在,我的问题是:

  1. 这会构造一个新字符串吗?

  2. 是否保证返回以空字符结尾的字符序列?

我有一小段代码用于演示。它似乎工作正常。 (参见魔杖盒 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/

相关文章:

c++ - 知道谁指向它的对象

c++ - 虚类的多重继承

c++ - 如何使用静态转换管理共享对象的生命周期?

c++ - 惯用地拆分 string_view

c++ - 为 unsigned char * 获取 strlen 的正确方法是什么?

c++ - Std::deque 直到程序退出才释放内存

c++ - 尽管有切片,为什么 static_cast 仍然可以使用空指针?

c++ - 将 `std::string` 临时值传递给 `std::string_view` 参数是否安全?

c++ - 比较 std::string_view 和子字符串 string_view