Tag: Copy copy on write when string is written
Programme II
Class string{private:char* _str; static int count;};
Set a static shaping variable to calculate the number of pointers to a piece of memory, minus 1 for each destructor, until it equals 0 (that is, no pointer is pointing to it) to release that memory, it seems feasible, but it is not!
This scheme only applies when the constructor is called only once, only one piece of memory, if the constructor is called multiple times to construct the object, the newly constructed object will change the value of count, then the previous memory cannot be released will cause a memory leak.
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/02/wKiom1b01hqizp5iAAB_YRhvMzo171.png "title=" Image.png "alt=" Wkiom1b01hqizp5iaab_yrhvmzo171.png "/>
Combined with the code below, we can see clearly how the scenario improves compared to the scenario one, as well as the flaws
#define_CRT_SECURE_NO_WARNINGS 1#include<iostream>using namespace std; #include < Assert.h>class string{public: string (char* str = "") //cannot strlen (NULL) { _str = new char[strlen (&NBSP;STR) + 1]; strcpy (_STR, &NBSP;STR); count++; } String (const string &s) { _str = s._str; count++; } string& operator= ( String& s) { _str = s._str; count++; return *this; } ~string () { if (--count == 0) { delete[] _str; _str = NULL; cout << "~ string "&NBSP;<<&NBSP;ENDL;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;} friend ostream& operator<< ( ostream& output, Const string &s); friend istream& operator>> ( Istream& input, const string &s);p rivate: char* _str; statIc int count;};o stream& operator<< ( ostream& output, const string & s) { output << s._str; return output;} Istream& operator>> ( istream& input, const string & s) { input >> s._str; return input;} int string::count = 0; //Initialize Countvoid test () { &NBSP;&NBSP;&NBSP;STRING&NBSP;S1 ("AAA"); string s2 (S1); string s3 = s2; cout << s1 << endl; cout << s2 << endl; cout << s3 << endl;} Int main () { test (); system ("pause"); return 0;}
Here are the other program link addresses:
Programme one:
http://iynu17.blog.51cto.com/10734157/1755179
Programme III:
http://iynu17.blog.51cto.com/10734157/1755208
Scenario Four: (recommended)
http://iynu17.blog.51cto.com/10734157/1755213
This article from "Yan Anyang" blog, declined reproduced!
Write-time copy (Scenario II)