使用c++(我的地方。e std::string) string(字符串)and where to use '\0' ending c string [duplicate]

时间:2023-01-06 21:16:05

This question already has an answer here:

这个问题已经有了答案:

Where to use std::string and where to use '\0' terminated C-string.
Basically I want to know what edges they have over each other.

在何处使用std::string ?在何处使用终止的C-string ?基本上,我想知道它们之间有哪些边。

2 个解决方案

#1


2  

c++ std::string:

c++ std::string:

strings, overall, are more secure then char*, Normally when you are doing things with char* you have to check things to make sure things are right, in the string class all this is done for you. Usually when using char*, you will have to free the memory you allocated, you don't have to do that with string since it will free its internal buffer when destructed. Strings work well with c++ stringstream, formated IO is very easy.

总的来说,字符串比char*更安全,通常当你用char*做事情时,你必须检查事情以确保事情是正确的,在string类中所有这些都是为你做的。通常在使用char*时,您必须释放所分配的内存,而不需要使用string,因为它在销毁时将释放其内部缓冲区。字符串在c++ stringstream中工作得很好,形式IO非常简单。

char

字符

Using char* gives you more control over what is happening "behind" the scenes, which means you can tune the performance if you need to.

使用char*可以让您对“幕后”发生的事情有更多的控制,这意味着如果需要,您可以调整性能。

#2


1  

zero terminated char* is used with C interfaces and std::string - in common c++ code. But there are not the only options - if you are really performance aware you may want to write your own string class (e.g. fixed length without dynamic memory allocation)

零终止字符*与C接口和std::string -在常见的c++代码中一起使用。但这并不是唯一的选择——如果您真正了解性能,那么您可能希望编写自己的字符串类(例如,没有动态内存分配的固定长度)

#1


2  

c++ std::string:

c++ std::string:

strings, overall, are more secure then char*, Normally when you are doing things with char* you have to check things to make sure things are right, in the string class all this is done for you. Usually when using char*, you will have to free the memory you allocated, you don't have to do that with string since it will free its internal buffer when destructed. Strings work well with c++ stringstream, formated IO is very easy.

总的来说,字符串比char*更安全,通常当你用char*做事情时,你必须检查事情以确保事情是正确的,在string类中所有这些都是为你做的。通常在使用char*时,您必须释放所分配的内存,而不需要使用string,因为它在销毁时将释放其内部缓冲区。字符串在c++ stringstream中工作得很好,形式IO非常简单。

char

字符

Using char* gives you more control over what is happening "behind" the scenes, which means you can tune the performance if you need to.

使用char*可以让您对“幕后”发生的事情有更多的控制,这意味着如果需要,您可以调整性能。

#2


1  

zero terminated char* is used with C interfaces and std::string - in common c++ code. But there are not the only options - if you are really performance aware you may want to write your own string class (e.g. fixed length without dynamic memory allocation)

零终止字符*与C接口和std::string -在常见的c++代码中一起使用。但这并不是唯一的选择——如果您真正了解性能,那么您可能希望编写自己的字符串类(例如,没有动态内存分配的固定长度)