航行日记

欢迎光临水精灵的小屋
数据加载中……

C++学习笔记二——常量字符串相同的情况

问:相同的字符串vc里面会采用同一地址,对吧?比如:
char *p1 = "asbsdg";
char *p2 = "asbsdg";
答:不见得。
问:那怎么判断?好像以前我看过试卷上有一题,就是默认它相同的。
答:没法判断。
问:/Gf /GF 不是取消重复字符串吗?怎么没作用。
答:/GF不是“取消”重复字符串,而是把常量字符串做统一映射,减少exe体积并提高执行效率。如果你的字符串不是常量,估计就没效果。
问:哦,就是另外分配内存时,当然不同了。那什么情况下,会不同地址?
答:非常量,或者编译器认为字符串会被人为改变的时候。
问:嗯。编译器认为字符串会被人为改变的时候,就是定义成volatile时?
答:不是。你可以试试:
const char * str1 = "This is constent string";
const char * str2 = "This is constent string";
const char str3[] = "This is constent string";
const char str4[] = "This is constent string";
char * str5 = "This is constent string";
问:结果是str1 = str2= str5, str3!= str4。你说的不相同出现在什么时候呢?除了字符数组外。
答:暂时找不到例子。
/GF的作用主要是作用于EXE文件而不是程序运行期的内存结构。
/Gf 是把相同的string 存储在EXE文件的同一个位置。
/GF是运行时,把这些string放入只读内存空间。如果你尝试改写它们的内容,就会弹出内存不可写的异常。
问:编译器默认有/Gf的选项吗?因为好像不加这个选项,如果我改写str5的字符,也会异常的。
答:默认应该是开启的。这个东西以前好像是叫“字符串折叠”。
问:呵呵,我现在就是不知道常量字符串地址不同的情况,那我先假设不成立,等遇到后再说。


现在,我关于相同字符串常量的地址赋值有点明白了,你呢?
最后,请大家看下面这段程序:
 const char * str1 = "This is constent string";
 const char * str2 = "This is constent string";
 const char str3[] = "This is constent string";
 const char str4[] = "This is constent string";
 char     *str5 = "This is constent string";
 str5[1] = 'a';          //exception
 str5 = (char *)0x1021 ; //normal
 str1 = (char *)0x1021 ; //normal

posted on 2005-02-04 11:40 水精灵 阅读(412) 评论(2)  编辑 收藏 所属分类: C++语言

评论

#1楼    回复  引用    

const char * str1 = "This is constent string";
const char * str2 = "This is constent string";
const char str3[] = "This is constent string";
const char str4[] = "This is constent string";
char *str5 = "This is constent string";
str5[1] = 'a'; //exception
str5 = (char *)0x1021 ; //normal
str1 = (char *)0x1021 ; //normal

上面这段代码我在ic++下编译没问题啊?? 还是要加什么编译选项??
2005-09-01 01:32 | java牌咖啡 [未注册用户]

#2楼    回复  引用    

在编译的时候会构造字符串池,如果对此地址内进行写操作,则将标为no const,如果所有链接时都没有进行写操作那就作为const,因此是安全的

如果是 const 类型,强制转换成 no const,进行写操作会出现写入非法错误,因为链接器把他放在“只读”段中,此时要设置段为可写,就可以了~
2007-03-18 16:59 | Ken [未注册用户]

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交