浅拷贝:被拷贝对象的所有变量都含有与之前对象变量相同的值,而其对所有对象的引用都指向之前的对象,在拷贝值的同时也拷贝了地址,造成两个指针指向同一个地址,在释放资源的时候,同一指针会被释放两次,造成资源泄露。
深拷贝:解决浅拷贝问题,在拷贝的同时,会重新开辟一段空间,用来存储被拷贝对象。
模拟实现String类
#include<iostream>
#include<string>
using namespace std;
class String{
public:
String(const char* str)
:_str(new char[strlen(str) + 1]){
strcpy(_str, str);
}
String(const String& d)
:_str(new char[strlen(d._str) + 1]){
strcpy(_str, d._str);
}
~String(){
cout << "~String" << endl;
delete[]_str;
_str = NULL;
}
//深拷贝的传统写法
/*String& operator=(const String& d){
if (_str == d.str){
return *this;
}
else{
delete[]_str;
_str = new char[strlen(d._str) + 1];
strcpy(_str, d._str);
}
return *this;
}*/
//深拷贝的简便写法
void Swap(String& d){
char* tmpchar;
tmpchar = this->_str;
this->_str = d._str;
d._str = tmpchar;
}
String& operator=(const String& d){
if (_str == d._str){
return *this;
}
else{
String tmp(d._str)
Swap(tmp);
return *this;
}
}
void Print_Str();
private:
char* _str;
};
void String::Print_Str(){
cout << this->_str << endl;
}
int main(){
String s1("abc");
String s2("def");
s1 = s2;
s1.Print_Str();
system("pause");
return 0;
}
来源:https://blog.csdn.net/weixin_43579220/article/details/99704352