C++ 写时拷贝

xiaoxiao2021-02-28  64

首先来了解浅拷贝和深拷贝: 1、浅拷贝,是指原对象与拷贝对象共用一份实体,仅仅是对象名字不同而已(类似引用,即对原对象起别名),其中任何一个对象的改变都会导致其他的对象也跟着改变。

2、深拷贝,是指拷贝一块跟原对象大小一样的数据块,即给新对象重新开辟一块空间,并将原对象的内容拷贝下来,这样原对象和现有对象指向各自的数据块,析构时释放各自的数据块。

3、写时拷贝(Copy On Write):给类增加一个引用计数,拷贝的时候增加一个引用计数,在对类成员进行拷贝的时候,之前的计数器加1,析构条件为当引用计数为1的时候,要对对象进行修改的时候再创建一份新的对象进行修改并改变指针指向。

#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; class String { public: String(const char* str = "") :_str(new char[strlen(str) + 4 + 1]) { if (_str == NULL) { *(int*)_str = 1; *(_str + 4) = '\0'; } else { *(int*)_str = 1;//前四个字节用来计数 _str += 4;//指针向后偏移四个字节,用来存储内容 strcpy(_str, str); } } String(const String &s) :_str(s._str) { ++(*(int*)(_str - 4));//向前偏移四个字节 计数器加一 } ~String() { if (_str == NULL) { return; } else { if (--(*(int*)(_str - 4)) == 0) { delete(_str - 4); _str = NULL; } } } String& operator=(const String&s) { if (_str != s._str) { if (--(*(int*)(_str - 4)) == 0) { delete(_str - 4); _str = NULL; } _str = s._str;//指向新空间 ++(*(int*)(_str - 4)); //将新空间的计数器加一 } return *this; } private: char* _str; }; int main() { String s1("abcd"); String s2(s1); String s3 = s2; String s4; s4 = s3; system("pause"); return 0; }

创建四个对象并赋值时: 调用析构函数之后:

转载请注明原文地址: https://www.6miu.com/read-45952.html

最新回复(0)