函数内的常量字符串是从程序静态存储区域分配的。内存在程序编译的时候就已经分配好了,和全局变量和static变量的分配方式是一样的。
那么请看下面程序:
程序成功打印出baidu_url::index()和baidu_url::index2(). 但打印baidu_url::index1会崩溃。
打印index成功是因为string类的写时拷贝技术。打印index1失败是因为:
对index1的调用过程分解如下:
const string & temp = baidu_url::index1();
cout << temp << end;
返回局部引用,使用时候自然崩溃。