std::字符串是否以"/0"结尾?

Is std::string terminated with '/0'?

本文关键字:结尾 字符串 是否 std      更新时间:2023-10-16
char *pt = "hello";
std::string str = "hello";

str是否也以 '/0' 结尾(是否以 null 结尾(?

无论 std::string 是否以 null 结尾,都是定义的实现。

定义后str的实际内容:

std::string str = "hello";

是字符'h''e''l''l''o',其size仅等于5个字符。

str 管理的缓冲区可能是空终止的,但不一定。

str.c_str()将为您提供一个const char*,它指向一个以 null 结尾的连续缓冲区(就像您的"hello"字符串文字一样(。

但请注意使用 &str[0],因为不能保证这指向连续缓冲区,也不能保证此缓冲区以 null 结尾。