C++ 中的 char* 与 std::string
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/801209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
char* vs std::string in c++
提问by
When should I use std::string
and when should I use char*
to manage arrays of char
s in C++?
我应该什么时候使用std::string
,什么时候应该使用C++char*
来管理char
s数组?
It seems you should use char*
if performance(speed) is crucial and you're willing to accept some of a risky business because of the memory management.
char*
如果性能(速度)至关重要,并且由于内存管理,您愿意接受一些有风险的业务,那么您似乎应该使用它。
Are there other scenarios to consider?
还有其他情况需要考虑吗?
采纳答案by Skurmedel
You can pass std::strings by reference if they are large to avoid copying, or a pointer to the instance, so I don't see any real advantage using char pointers.
如果 std::strings 很大以避免复制或指向实例的指针,您可以通过引用传递它们,因此我看不到使用 char 指针的任何真正优势。
I use std::string/wstring for more or less everything that is actual text. char *
is useful for other types of data though and you can be sure it gets deallocated like it should. Otherwise std::vector is the way to go.
我或多或少地使用 std::string/wstring 来表示所有实际文本。char *
但是对于其他类型的数据很有用,您可以确定它会像它应该的那样被释放。否则 std::vector 是要走的路。
There are probably exceptions to all of this.
所有这些可能都有例外。
回答by Gal Goldman
My point of view is:
我的观点是:
- Never use char * if you don't call "C" code.
- Always use std::string: It's easier, it's more friendly, it's optimized, it's standard, it will prevent you from having bugs, it's been checked and proven to work.
- 如果您不调用“C”代码,切勿使用 char *。
- 始终使用 std::string:它更容易,更友好,它经过优化,它是标准的,它可以防止您出现错误,它已经过检查并证明有效。
回答by Suma
Raw string usage
原始字符串用法
Yes, sometimes you really can do this. When using const char *, char arrays allocated on the stack and string literals you can do it in such a way there is no memory allocation at all.
是的,有时你真的可以做到这一点。当使用 const char *、在堆栈上分配的 char 数组和字符串文字时,您可以这样做,根本没有内存分配。
Writing such code requires often more thinking and care than using string or vector, but with a proper techniques it can be done. With proper techniques the code can be safe, but you always need to make sure when copying into char [] you either have some guarantees on the lenght of the string being copied, or you check and handle oversized strings gracefully. Not doing so is what gave the strcpy family of functions the reputation of being unsafe.
编写这样的代码通常比使用字符串或向量需要更多的思考和关心,但只要使用适当的技术,就可以做到。使用适当的技术,代码可以是安全的,但你总是需要确保在复制到 char [] 时,你要么对被复制的字符串的长度有一些保证,要么优雅地检查和处理过大的字符串。不这样做是导致 strcpy 函数系列不安全的原因。
How templates can help writing safe char buffers
模板如何帮助编写安全的字符缓冲区
As for char [] buffers safety, templates can help, as they can create an encapsulation for handling the buffer size for you. Templates like this are implemented e.g. by Microsoft to provide safe replacements for strcpy. The example here is extracted from my own code, the real code has a lot more methods, but this should be enough to convey the basic idea:
至于 char [] 缓冲区安全,模板可以提供帮助,因为它们可以创建一个封装来为您处理缓冲区大小。像这样的模板是由微软实现的,以提供 strcpy 的安全替代品。这里的例子摘自我自己的代码,真正的代码有很多方法,但这应该足以传达基本思想:
template <int Size>
class BString
{
char _data[Size];
public:
BString()
{
_data[0]=0;
// note: last character will always stay zero
// if not, overflow occurred
// all constructors should contain last element initialization
// so that it can be verified during destruction
_data[Size-1]=0;
}
const BString &operator = (const char *src)
{
strncpy(_data,src,Size-1);
return *this;
}
operator const char *() const {return _data;}
};
//! overloads that make conversion of C code easier
template <int Size>
inline const BString<Size> & strcpy(BString<Size> &dst, const char *src)
{
return dst = src;
}
回答by thesamet
One occasion that you MUST use char*
and not std::string
is when you need static string constants. The reason for that is that you don't have any control on the order modules initialize their static variables, and another global object from a different module may refer to your string before it's initialized. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Static_and_Global_Variables
您必须使用char*
而不是的一种情况std::string
是您需要静态字符串常量。原因是您无法控制模块初始化其静态变量的顺序,并且来自不同模块的另一个全局对象可能会在初始化之前引用您的字符串。http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Static_and_Global_Variables
std::string
pros:
std::string
优点:
- manages the memory for you (the string can grow, and the implementation will allocate a larger buffer you)
- Higher-level programming interface, works nicely with the rest of STL.
- 为您管理内存(字符串可以增长,并且实现将为您分配更大的缓冲区)
- 高级编程接口,与 STL 的其余部分很好地配合。
std::string
cons:
- two distinct STL string instances can not share the same underlying buffer. So if you pass by value you always get a new copy.
- there is some performance penalty, but I'd say unless your requirements are special it's negligible.
std::string
缺点: - 两个不同的 STL 字符串实例不能共享相同的底层缓冲区。因此,如果您按值传递,您总是会得到一个新副本。- 有一些性能损失,但我会说除非您的要求很特殊,否则可以忽略不计。
回答by Jér?me
You should consider to use char*
in the following cases:
您应该考虑char*
在以下情况下使用:
- This array will be passed in parameter.
- You know in advance the maximum size of your array (you know it OR you impose it).
- You will not do any transformation on this array.
- 该数组将传入参数。
- 您事先知道数组的最大大小(您知道或强加它)。
- 您不会对该数组进行任何转换。
Actually, in C++, char*
are often use for fixed small word, as options, file name, etc...
实际上,在 C++ 中,char*
经常用于固定的小词,如选项、文件名等...
回答by user88637
When to use a c++ std::string:
何时使用 C++ std::string:
- strings, overall, are more secure than 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, formatted IO is very easy.
- 总的来说,strings 比 char* 更安全,通常当你使用 char* 做事情时,你必须检查事情以确保事情是正确的,在 string 类中所有这些都是为你完成的。
- 通常,在使用 char* 时,您必须释放分配的内存,而不必对 string 执行此操作,因为它会在销毁时释放其内部缓冲区。
- 字符串与 c++ stringstream 配合良好,格式化 IO 非常容易。
When to use char*
何时使用 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* 可以让您更好地控制“幕后”发生的事情,这意味着您可以根据需要调整性能。
回答by Nemanja Trifunovic
Use (const) char* as parameters if you are writing a library. std::string implementations differ between different compilers.
如果您正在编写库,请使用 (const) char* 作为参数。std::string 实现在不同的编译器之间有所不同。
回答by n0rd
If you want to use C libraries, you'll have to deal with C-strings. Same applies if you want to expose your API to C.
如果要使用 C 库,则必须处理 C 字符串。如果您想将 API 公开给 C,同样适用。
回答by n0rd
You can expect most operations on a std::string (such as e.g. find
) to be as optimized as possible, so they're likely to perform at least as well as a pure C counterpart.
您可以期望 std::string 上的大多数操作(例如 eg find
)尽可能优化,因此它们的性能可能至少与纯 C 对应物一样好。
It's also worth noting that std::string iterators quite often map to pointers into the underlying char array. So any algorithm you devise on top of iterators is essentially identical to the same algorithm on top of char * in terms of performance.
还值得注意的是 std::string 迭代器经常映射到指向底层 char 数组的指针。因此,就性能而言,您在迭代器之上设计的任何算法本质上都与 char * 之上的相同算法相同。
Things to watch out for are e.g. operator[]
- most STL implementations do not perform bounds checking, and should translate this to the same operation on the underlying character array. AFAIK STLPort can optionally perform bounds checking, at which point this operator would be a little bit slower.
需要注意的事情是例如operator[]
- 大多数 STL 实现不执行边界检查,并且应该将其转换为对底层字符数组的相同操作。AFAIK STLPort 可以选择执行边界检查,此时此运算符会慢一点。
So what does using std::string gain you? It absolves you from manual memory management; resizing the array becomes easier, and you generally have to think less about freeing memory.
那么使用 std::string 有什么好处呢?它使您免于手动内存管理;调整数组大小变得更容易,并且您通常不必考虑释放内存。
If you're worried about performance when resizing a string, there's a reserve
function that you may find useful.
如果您在调整字符串大小时担心性能问题,那么reserve
您可能会发现有一个函数很有用。
回答by RvdK
if you are using the array of chars in like text etc. use std::string more flexible and easier to use. If you use it for something else like data storage? use arrays (prefer vectors)
如果您在类似文本等中使用字符数组,请使用 std::string 更灵活且更易于使用。如果您将其用于数据存储等其他用途?使用数组(首选向量)