字符* VS的std ::在C ++字符串 [英] char* vs std::string in c++
问题描述
当我应该使用的std ::字符串
时,我应该使用的char *
管理<$阵列C $ C>字符 S IN C ++?
When should I use std::string
and when should I use char*
to manage arrays of char
s in C++?
看来你应该使用的char *
如果性能(速度)是至关重要的,你愿意接受,因为内存管理的一些有风险的业务。
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.
有其他的方案以供参考?
Are there other scenarios to consider?
推荐答案
您可以通过引用传递的std ::字符串,如果他们是大,以避免复制或指针实例,因此我没有看到任何真正的优势使用字符指针。
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 :: string的/ wstring的因为这是实际文本或多或少的一切。 的char *
是其他类型的数据有用的,而且你可以肯定它得到像它应该释放。否则的std ::向量是要走的路。
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.
有可能是例外了这一切。
There are probably exceptions to all of this.
这篇关于字符* VS的std ::在C ++字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!