问题描述
我已经读过几个地方,在 c_str()
和 data()
实现)是 c_str()
始终为null终止,而 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?
推荐答案
文档是正确的。如果您需要,请使用一个空的终止字符串。
The documentation is correct. Use c_str()
if you want a null terminated string.
如果实现者发现实现,你不必担心,仍然使用 data()
如果你不需要字符串为null终止,在某些实现中它可能会表现得比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终止。根据:返回的数组为null终止,即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."
这篇关于string c_str()vs. data()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!