您的位置:首页 > 运维架构

deep copy and shallow copy

2016-11-23 21:55 288 查看
///在有指针的情况下,浅拷贝只是增加了一个指针指向已经存在的内存,
///而深拷贝就是增加一个指针并且申请一个新的内存,使这个增加的指针指向这个新的内存,
///采用深拷贝的情况下,释放内存的时候就不会出现在浅拷贝时重复释放同一内存的错误!
///举个栗子
///最能体现深层拷贝与浅层拷贝的,就是‘=’的重载。

#include<iostream>
#include<cstring>
using namespace std;
class String
{
char *m_str;
public:
String(char *s)
{
m_str=s;
}

String(){};

/*String & operator=(const String s)

{

m_str=s.m_str;

return *this;
}*/
String & operator=(const String & s)///=重载其是就是实现了浅拷贝原因。是由于对象之中含有指针数据类型.s1,s2恰好指向同一各内存。
///所以是浅拷贝。而你如果修改一下原来的程序:
{

cout << strlen(m_str) << endl;
if(strlen(m_str)!=strlen(s.m_str))
{
cout << strlen(s.m_str) << endl;
m_str=new char[strlen(s.m_str)+1];
}

if(strcmp(this->m_str,s.m_str))
strcpy(m_str,s.m_str);

return *this;
}

void show()
{
cout << m_str << endl;
}

};

int main()

{
String s1("abc");
String s2("abcd");

s2=s1;

s2.show();

}

/*
abc
*/
///要注意赋值与初始化的本质区别~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: