string c_str() vs. data()(字符串 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:字符串 c_str() 与 data()
				
        
 
            
        基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				