C + + String write-time replication

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.