String copy on write: After assigning the string str1 to Str2, str2 and str1 share memory unless STR1 's content has been changed. When STR1 is modified, STL opens up memory space for str2 and initializes it.
#include <cstring>#include<string>#include<cstdio>#include<iostream>using namespacestd;voidfun1 () {stringS1 ="Hello, world!."; stringS2 =S1; cout<<"Before:"<< S2 <<Endl; Char* ptr = const_cast<Char*>(S1.c_str ()); *ptr ='F'; cout<<"After :"<< S2 <<Endl;}voidfun2 () {stringS1 ="Hello, world!."; stringS2 =S1; cout<<"Before:"<< S2 <<Endl; s1[0] ='F'; cout<<"After :"<< S2 <<Endl;}intMain () {cout<<"fun1:"<<Endl; Fun1 (); cout<<"fun2:"<<Endl; Fun2 (); return 0;}
Note: In fun1, modifying the S1 behavior through char* does not trigger the STL copy operation because the STL does not consider the S1 modification by char* to be a modification to the string S1.
C + + String write-time replication