大佬教程收集整理的这篇文章主要介绍了c – 为什么std :: string_view :: data不包含空终止符?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <String_view> #include <iostream> using namespace std::string_view_literals; void foo(std::string_view msg) { std::cout << msg.data() << '\n'; // undefined behavior if 'msg' is not null- // terminated // std::cout << msg << '\n'; is not undefined because operator<< uses // iterators to print 'msg',but that's not the point } int main() { foo("Hello"sv); // not null-terminated - undefined behavior foo("foo"); // same,even more dangerous }
原因是std::string_view
可以存储非空终止字符串,并且在调用数据时不包含空终止符.这是非常有限的,为了使上面的代码定义行为,我必须构造一个std :: String:
std::string str{ msg }; std::cout << str.data() << '\n';
在这种情况下,这确实使std :: String_view变得不必要,我仍然要复制传递给foo的字符串,那么为什么不使用移动语义并将msg更改为std :: String?这可能会更快,但我没有衡量.
无论哪种方式,每次我想要将const char *传递给只接受const char *的函数时,必须构造一个std :: String是有点不必要的,但是必须有一个理由让委员会以这种方式决定它.
那么,为什么std::string_view::data
不会返回像std :: String :: data这样的以null结尾的字符串?
以上是大佬教程为你收集整理的c – 为什么std :: string_view :: data不包含空终止符?全部内容,希望文章能够帮你解决c – 为什么std :: string_view :: data不包含空终止符?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。