本文介绍了字符串 c_str() 与 data()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过几个地方,c_str()data()(在 STL 和其他实现中)的区别在于 c_str()code> 总是空终止而 data() 不是.就我在实际实现中所见,它们要么执行相同操作,要么data() 调用 c_str().

I have read several places that the difference between c_str() and data() (in STL and other implementations) is that c_str() is always null terminated while data() is not.As far as I have seen in actual implementations, they either do the same or data() calls c_str().

我在这里错过了什么?在哪些场景下使用哪个更正确?

What am I missing here?Which one is more correct to use in which scenarios?

推荐答案

文档是正确的.使用 c_str() 如果你想要一个空终止字符串.

The documentation is correct. Use c_str() if you want a null terminated string.

如果实施者碰巧实施了data()c_str() 而言你不必担心,如果你不需要字符串以空终止,仍然使用 data() ,在某些实现中,它可能会比 c_str() 表现得更好.

If the implementers happend to implement data() in terms of c_str() you don't have to worry, still use data() if you don't need the string to be null terminated, in some implementation it may turn out to perform better than c_str().

字符串不一定必须由字符数据组成,它们可以由任何类型的元素组成.在这些情况下 data() 更有意义.c_str() 在我看来,只有当你的字符串元素是基于字符的时候才真正有用.

strings don't necessarily have to be composed of character data, they could be composed with elements of any type. In those cases data() is more meaningful. c_str() in my opinion is only really useful when the elements of your string are character based.

额外:从 C++11 开始,两个函数必须相同.即 data 现在需要以 null 结尾.根据cppreference:返回的数组以空值结尾,即, data() 和 c_str() 执行相同的功能."

Extra: In C++11 onwards, both functions are required to be the same. i.e. data is now required to be null-terminated. According to cppreference: "The returned array is null-terminated, that is, data() and c_str() perform the same function."

这篇关于字符串 c_str() 与 data()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:58