C++的深拷贝实现
2016-03-20 20:14
351 查看
深拷贝 #include<iostream> #include<stdio.h> using namespace std; class String { public : String(char* str="") : _str(new char [strlen(str )+1]) { strcpy(_str , str); } String(const String& s)//拷贝构造 :_str(NULL) { String tmp(s._str ); swap(_str,tmp._str ); } String& operator =(const String& s ) { swap(_str,s._str ); return *this; } ~ String() { if(_str) { delete[] _str ; } } private : char* _str ; } void test1 () { String s1("s1"); String s2(s1); String s3("s3"); String s4(s3); s1=s4; } int main() { test1(); system("pause"); return 0; } 引用计数浅拷贝 #include<iostream> #include<stdio.h> using namespace std; class String { public : String(char* str="") : _str(new char [strlen(str )+1]) ,_pCount(new int(1)) { strcpy(_str , str); } String( String& s) :_str(s._str ) ,_pCount(s._pCount) { ++(*_pCount); } String& operator =(const String& s ) { if(--(*_pCount)==0) { delete _pCount; delete[] _str; } _str=s._str ; _pCount=s._pCount ; ++(*_pCount); return *this; } ~ String() { if (--(*_pCount)==0&&_str ) { delete _pCount; delete[] _str ; } } private : char* _str ; int* _pCount; }; void testcount () { String s1("s1"); String s2(s1); String s3(s2); String s4("s4"); String s5 (s4); s1=s4; } int main() { testcount(); system("pause"); return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Python动态类型的学习---引用的理解
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#中使用DataContractSerializer类实现深拷贝操作示例
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C#中4种深拷贝方法介绍
- C++联合体转换成C#结构的实现方法
- 简单谈谈C#中深拷贝、浅拷贝
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题