一、代码
示例:在s串重新赋值后, a,b重新赋值结果导致程序崩溃。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "abcdefg";
char& d = s[0];
char& e = s[1];
char& a = s[2];
char& b = s[3];
a = '1';
b = '2';
cout << s << endl;
cout << (int*)s.c_str() << endl;
s = "pppppppppppppppppppppppppp";
a = '1';
b = '2';
cout << s << endl;
cout << (int*)s.c_str() << endl;
}
Q:引用的存储的是对象的指针,s串重新赋值,地址没有改变啊,为什么a,b第二次赋值会导致程序崩溃呢?
A:string不超过16字节的栈上存储,如果超出16字节则在堆上分配,所以对s第二次赋值内容过多,栈内存就被释放,会重新申请堆内存。