且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++中string和char[]类型的区别

更新时间:2021-07-08 01:44:35

char 数组就是这样 - 一个字符数组:

A char array is just that - an array of characters:

  • 如果在堆栈上分配(如您的示例中),它将始终占用例如.256 字节,无论它包含多长的文本
  • 如果在堆上分配(使用 malloc() 或 new char[]),您负责之后释放内存,并且您将始终拥有堆分配的开销.
  • 如果将超过 256 个字符的文本复制到数组中,它可能会崩溃、产生丑陋的断言消息或导致程序中其他地方出现无法解释的(错误)行为.
  • 要确定文本的长度,必须逐个字符地扫描数组以获得 字符.

字符串是一个包含字符数组的类,但会自动为您管理它.大多数字符串实现都有一个由 16 个字符组成的内置数组(因此短字符串不会对堆造成碎片),并将堆用于更长的字符串.

A string is a class that contains a char array, but automatically manages it for you. Most string implementations have a built-in array of 16 characters (so short strings don't fragment the heap) and use the heap for longer strings.

您可以像这样访问字符串的字符数组:

You can access a string's char array like this:

std::string myString = "Hello World";
const char *myStringChars = myString.c_str();

C++ 字符串可以包含嵌入的 字符,无需计算即可知道它们的长度,对于短文本比堆分配的字符数组更快,并保护您免受缓冲区溢出的影响.此外,它们更具可读性和易用性.

C++ strings can contain embedded characters, know their length without counting, are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they're more readable and easier to use.

然而,C++ 字符串并不(非常)适合跨 DLL 边界使用,因为这将要求此类 DLL 函数的任何用户确保他使用完全相同的编译器和 C++ 运行时实现,以免他的字符串类冒险表现不同.

However, C++ strings are not (very) suitable for usage across DLL boundaries, because this would require any user of such a DLL function to make sure he's using the exact same compiler and C++ runtime implementation, lest he risk his string class behaving differently.

通常,字符串类也会在调用堆上释放其堆内存,因此如果您使用的是运行时的共享(.dll 或 .so)版本,它只能再次释放内存.

Normally, a string class would also release its heap memory on the calling heap, so it will only be able to free memory again if you're using a shared (.dll or .so) version of the runtime.

简而言之:在所有内部函数和方法中使用 C++ 字符串.如果您曾经编写过 .dll 或 .so,请在您的公共(dll/so-exposed)函数中使用 C 字符串.

In short: use C++ strings in all your internal functions and methods. If you ever write a .dll or .so, use C strings in your public (dll/so-exposed) functions.