如何将std :: string_view转换为const char *? [英] How you convert a std::string_view to a const char*?
问题描述
使用gcc-7.1和标志 -std = c ++ 17
进行编译,以下程序会引发错误:
Compiling with gcc-7.1 with the flag -std=c++17
, the following program raises an error:
#include <string_view>
void foo(const char* cstr) {}
void bar(std::string_view str){
foo(str);
}
错误消息是
In function 'void bar(std::string_view)':
error: cannot convert 'std::string_view {aka std::basic_string_view<char>}' to 'const char*' for argument '1' to 'void foo(const char*)'
foo(str);
我很惊讶没有转换为 const char *
,因为其他库(abseil,bde)提供了类似的 string_view
类,这些类隐式转换为 const char *
。
I'm surprised there is no conversion to const char*
because other libraries (abseil, bde), provide similar string_view
classes which implicitly convert to const char*
.
推荐答案
A std :: string_view
不提供转换到 const char *
的原因,因为它不存储以空值结尾的字符串。它基本上存储了指向第一个元素的指针以及字符串的长度。这意味着您不能将其传递给期望以空值终止的字符串的函数,例如 foo
(您还打算如何获取大小?),期望为 const char *
,因此认为它不值得。
A std::string_view
doesn't provide a conversion to a const char*
because it doesn't store a null-terminated string. It stores a pointer to the first element, and the length of the string, basically. That means that you cannot pass it to a function expecting a null-terminated string, like foo
(how else are you going to get the size?) that expects a const char*
, and so it was decided that it wasn't worth it.
如果您确定知道自己拥有在您的视图中以空值结尾的字符串中,可以使用 std :: string_view :: data
。
If you know for sure that you have a null-terminated string in your view, you can use std::string_view::data
.
如果不是,则应重新考虑是否使用 std :: string_view
首先是个好主意,因为如果您想要一个保证以空值结尾的字符串,则 std :: string
想。对于单行代码,可以使用 std :: string(object).data()
。
If you're not you should reconsider whether using a std::string_view
in the first place is a good idea, since if you want a guaranteed null-terminated string std::string
is what you want. For a one-liner you can use std::string(object).data()
.
这篇关于如何将std :: string_view转换为const char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!