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 */ ///要注意赋值与初始化的本质区别~
相关文章推荐
- 深拷贝与浅拷贝(Deep Copy and Shallow Copy)
- copy — Shallow and deep copy operations
- NET深入学习笔记(4):深拷贝与浅拷贝(Deep Copy and Shallow Copy)
- .NET深入学习笔记(4):深拷贝与浅拷贝(Deep Copy and Shallow Copy)(转载)
- python deep copy and shallow copy
- shallow copy and deep copy (浅拷贝 vs 深拷贝)
- Deep copy and shallow copy
- Python: Shallow and deep copy operations
- Shallow Copy and Deep Copy
- Shallow and Deep Copy
- difference between Python shallow copy and deep copy
- Deep Copy and Shallow Copy
- shallow copy and deep copy in Prototype Pattern
- [导入].NET深入学习笔记(4):深拷贝与浅拷贝(Deep Copy and Shallow Copy)
- Difference between shallow copy and deep copy?
- shallow copy and deep copy
- 深拷贝与浅拷贝(Deep Copy and Shallow Copy)
- Java Clone, Shallow Copy and Deep Copy
- .NET深入学习笔记(4):深拷贝与浅拷贝(Deep Copy and Shallow Copy) 推荐
- 【转】.NET深入学习笔记(4):深拷贝与浅拷贝(Deep Copy and Shallow Copy)