写时拷贝方案分析 copy on write
来源:互联网 发布:nginx m3u8 点播 编辑:程序博客网 时间:2024/06/08 15:25
copy on write
- 写时拷贝是浅拷贝解决浅拷贝析构冲突的一种解决方案
- 相比较于深拷贝,写时浅拷贝占用空间少(相同内容不新开辟空间),复制效率高
几种写时拷贝方案比较
int _refCount (错误)
class String1{public: String1(char* str) :_refCount(1) { _str = (char*)malloc(strlen(str) + 1); strcpy(_str, str); } String1(String1& s) :_str(s._str), _refCount(++s._refCount) {} ~String1() { _refCount--; if (_refCount == 0) free(_str); } String1& operator=(String1 s) { if (_str != s._str) { if (_refCount == 1) free(_str); _str = s._str; _refCount = ++s._refCount; } }private: char* _str; int _refCount;};
用这种方法进行写时拷贝,对一个对象进行析构 _refCount– 时,访问不到其他相同对象的 _refCount , 只要进行拷贝或赋值,就会造成内存泄漏。
static int _refCount (错误)
class String2{ char* _str; static int _refCount;};int String2::_refCount = 0;
当出现不同的对象时,就会出现错误,_refCount 是唯一的。
int* _refCount (正确)
class String3{public: String3(char* str) { _str = (char*)malloc(strlen(str) + 1); strcpy(_str, str); _refCount = new int(1); } String3(String3& s) { _str = (char*)malloc(strlen(s._str) + 1); strcpy(_str, s._str); _refCount = s._refCount; (*_refCount)++; } String3& operator=(String3 s) { if (_str != s._str) { free(_str); _str = s._str; _refCount = s._refCount; (*_refCount)++; } return *this; } ~String3() { if (--(*_refCount) == 0) { free(_str); delete _refCount; } }private: char* _str; int* _refCount;};
##隐含的 int 指针
在初始化 _str 时,在其前面多申请四字节空间,存放 int 型变量作计数器
阅读全文
0 0
- 写时拷贝方案分析 copy on write
- 写时拷贝Copy-On-Write技术
- 写时拷贝技术(copy-on-write)
- 写时拷贝技术:Copy-On-Write
- 写时拷贝(copy on write)
- STL的写时拷贝(Copy-On-Write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)--COW
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Linux写时拷贝技术(copy-on-write)
- Vue2学习笔记:组件(Component)
- FZU 2261 浪里个浪 (多源最短路)(福州大学第十四届程序设计竞赛)
- java中函数问题Function
- 交换链表中相邻节点的位置
- 操作系统之存储器管理
- 写时拷贝方案分析 copy on write
- MySQL 之数据备份与恢复
- Visual Studio 团队管理器无法连接 TF31003(TF31001,TF31002)
- Some Meritorious Material about WEB . TBC
- Spring入门到精通(二)
- 617. Merge Two Binary Trees
- 电子笔记本的思考(1)(ver0.2)
- 暑假flag
- Dubbo 管理控制台安装