使用op[]修改std::string超出其大小的影响
Effects of modifying std::string using op[] beyond its size?
我有点困惑如何修改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
输出管道使控制字符可见,我看到:
这解释了你所看到的:你覆盖了' '
结束符,但你没有覆盖单独存储的大小。
正如kec所指出的,您可能已经看到了垃圾,除非您足够幸运,在额外的字符后面有一个额外的零字节。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 为什么擦除方法会影响结束方法
- 内联如何影响模块接口中的成员函数
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 在容量内调整矢量大小时的性能影响
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- std::string 的运算符<是否应该受到当前区域设置的影响?
- _T宏是否影响 std::string 构造函数
- char的实现定义是否会影响std::string
- 使用op[]修改std::string超出其大小的影响