zoukankan      html  css  js  c++  java
  • 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的修改。

  • 相关阅读:
    2019.9.25 初级数据结构——树状数组
    2019.9.29 陪审团
    2019.9.27 硬币
    0070-星星阵
    0069-简单的回文数问题
    0068-简单的求和问题
    0067-水仙花数
    0066-若干个数求和问题
    0065-数方块
    0064-简单的平方和
  • 原文地址:https://www.cnblogs.com/taiyang-li/p/6019914.html
Copyright © 2011-2022 走看看