首页 > 代码库 > c++ string写时复制

c++ string写时复制

  string写时复制:将字符串str1赋值给str2后,除非str1的内容已经被改变,否则str2和str1共享内存。当str1被修改之后,stl才为str2开辟内存空间,并初始化。

  

#include <cstring>
#include <string>
#include <cstdio>
#include <iostream>
using namespace std;

void fun1()
{
  string s1 = "hello, world!";
  string s2 = s1; 

  cout << "before: " << s2 << endl;
  char* ptr = const_cast<char*>(s1.c_str());
  *ptr = f;
  cout << "after: " << s2 << endl;
}

void fun2()
{
  string s1 = "hello, world!";
  string s2 = s1; 

  cout << "before: " << s2 << endl;
  s1[0] = f;
  cout << "after: " << s2 << endl;
}

int main()
{
  cout << "fun1: " << endl;
  fun1();

  cout << "fun2: " << endl;
  fun2();

  return 0;
}

注意:fun1中,通过char*修改s1行为,并不会触发stl的复制操作,因为stl并不认为通过char* 对s1的修改是对string s1的修改。

c++ string写时复制