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的修改。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM