北飞

非一般的感觉
随笔 - 9, 文章 - 3, 评论 - 0, 引用 - 0
数据加载中……

stl string 写时拷贝

对于stl中的string的写时拷贝还是最近才发现的,起因是应用类似于如下的代码:

1string str = "beifei";
2string str1 = str;
3sprintf((char*)str.c_str(),"xiao");
4
打印str,str1发现两者的内容是一样的,翻阅资料才发现string采用的是写时拷贝,至于写操作是则是特定的操作,如赋值操作符,下标操作符等,像以上的代码属于hack一下,绕开了写时拷贝的接口,所以才会出现以上情况。

下面再举个例子,用以加深印象:

 1#include <iostream>
 2#include <string>
 3using namespace std;
 4
 5int main()
 6{
 7    string str1= "beifei";
 8    string str2 = str1;
 9
10    cout << (void*)str1.c_str() << endl;
11    cout << (void*)str2.c_str() << endl;
12
13    str1 = "xieyang";
14    cout << (void*)str1.c_str() << endl;
15    cout << (void*)str2.c_str() << endl;
16
17    return 0;
18}
以上代码的输出结果是:
0x502028
0x502028
0x502058
0x502028
我们可以看到,只要进行赋值之后,两个string对象内部指向的字符串地址才会发生变化,也只有这个时候才会发现写时拷贝。

posted on 2011-04-08 16:17 北飞 阅读(711) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理