c++ 深浅拷贝(传统写法 xain'dai'xie'fa)
2016-03-12 13:30
447 查看
简单的赋值浅拷贝 class String { public : String(const char* str) : _str(new char [strlen(str )+1]) { strcpy(_str , str); } String(const String& str) : _str(str ._str) {} String& operator =(const String& str ) { if (this != &str) { _str = str ._str; } return *this; } ~ String() { if (_str ) { delete[] _str ; } } private : char* _str ; }; void TestString () { String s1 ("hello world!"); String s2 = s1; } 当类里面有指针对象时,进行简单赋值的浅拷贝,两个对象指向同一块内存,存在崩溃的问题!这里我们要进行深拷贝。 #define _CRT_SECURE_NO_WARNINGS //#include<iostream> //using namespace std; //class String //{ //public: // //String(const char *str) :_str(new char[strlen(str)+1])//深层拷贝 // //{ // // strcpy(_str, str); // //} // String(char *str = "") :_str(new char[strlen(str)+1]) // { // strcpy(_str, str); // } // //String(String & s) // //{ // // _str = s._str; // //} 浅拷贝测试 // String(const String & s) :_str(new char[strlen(s._str)+1]) //深拷贝 // { // strcpy(_str, s._str); // } ///* String& operator=( const String&s) // { // if (this != &s) // { // char *p = _str; // _str = new char[strlen(s._str) + 1]; // delete[]p; // strcpy(_str, s._str); // // } // return *this; // } */ //传统写法 // // //现代写法 // String& operator=( String&s) // { // if (this != &s) // { // String tmp(s); // std::swap(_str, tmp._str); // } // return *this; // } // // // ~String() // { // if (_str) // delete[]_str; // } //private: // char *_str; // //}; //int main() //{ // String s1("abcd"); // String s2(s1); // String s3("qwer"); // s3 = s1; // String s4; // s4 = s3; // return 0; //} #include<iostream>// 引用计数 using namespace std; class String { public: String(char *str = "") :_str(new char[strlen(str) + 1]), _refCount(new int(1)) { strcpy(_str, str); } String(const String& s) { _str = s._str; _refCount = s._refCount; ++*_refCount; } ~String() { if (--*_refCount == 0) delete[]_str; } private: char *_str; int *_refCount;// }; int main() { String s1("abcde"); String s2(s1); String s3("qwer"); String s4(s3); return 0; }
![](http://s3.51cto.com/wyfs02/M02/7D/3A/wKioL1bi5BLy-EuwAAA2G-b6950394.png)
![](http://s2.51cto.com/wyfs02/M01/7D/3C/wKiom1bi4-DQcoywAABBHjrrzUo836.png)
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性