使用op[]修改std::string超出其大小的影响

Effects of modifying std::string using op[] beyond its size?

本文关键字:影响 string op 修改 std 使用      更新时间:2023-10-16

我有点困惑如何修改std::字符串超出其大小的处理?在我尝试的一个示例中,它允许我使用op[]修改字符串超出其大小(我知道标准并没有阻止您这样做)。然而,当我使用cout打印字符串时,它打印原始字符串,但当我打印cstr()返回的内容时,它打印修改后的版本。它是如何跟踪这两种尺寸(3 &5) ?。

#include <string>
#include <iostream>
using namespace std;
int main(void) {
    std::string a = "abc";
    cout << "str before     : " << a << endl;
    const char * charPtr = a.c_str ();
    cout << "c_str before   : " << charPtr << endl;
    cout << "str size / capacity : " << a.size () << ", " << a.capacity () << endl;
    a[3] = 'd';
    a[4] = 'e';
    cout << "str after      : " << a << endl;
    const char * charPtr2 = a.c_str ();
    cout << "c_str after    : " << charPtr2 << endl;
    cout << "str size / capacity : " << a.size () << ", " << a.capacity () << endl;
    return 0;
}

输出:STR before: abc
C_str before: abc
STR大小/容量:3,3
STR after: abc
C_str after: abcde
STR大小/容量:3,3

虽然你已经得到了一个正确的评论,说行为是未定义的,但也有一些值得实际回答的东西。

c++ string对象可以包含任何您喜欢的字符序列。c风格字符串以第一个''结束。因此,c++ string对象必须以外的位置存储大小,而不是搜索'':它可能包含嵌入的''字符。

#include <string>
#include <iostream>
int main() {
  std::string s = "abc";
  s += '';
  s += "def";
  std::cout << s << std::endl;
  std::cout << s.c_str() << std::endl;
}

运行这个,并通过cat -v输出管道使控制字符可见,我看到:

<>之前abc ^ @def美国广播公司之前

这解释了你所看到的:你覆盖了''结束符,但你没有覆盖单独存储的大小。

正如kec所指出的,您可能已经看到了垃圾,除非您足够幸运,在额外的字符后面有一个额外的零字节。