shallow copy and deep copy(浅拷贝与深拷贝)
C++03性能上长期被诟病的原因有一点就是其耗时且不必要的深度拷贝。
简单的理解就是浅拷贝就是拷贝指针,深拷贝就是重新分配内存拷贝数据
- The default copy constructor and default assignment operators do shallow copies, which is fine for classes that contain no dynamically allocated variables.
- Classes with dynamically allocated variables need to have a copy constructor and assignment operator that do a deep copy.
- The assignment operator is usually implemented using the same code as the copy constructor, but it checks for self-assignment, returns *this, and deallocates any previously allocated memory before deep copying.
- If you don’t want a class to be copyable, use a private copy constructor and assignment operator prototype in the class header.
1. 默认拷贝构造或者默认赋值操作执行的浅拷贝,主要用于没有包含动态分配内存的类
2. 有动态内存分配的类则不能使用某人拷贝构造或者默认的赋值操作,并且需要执行深拷贝
3. 赋值操作和拷贝构造代码相同,但是多了检查self-assignment,返回*this,以及释放前面分配的内存。
4. 如果不希望该类可以拷贝,则使用private类型的拷贝构造和赋值操作
考考资料:
http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/
http://stackoverflow.com/questions/2657810/deep-copy-vs-shallow-copy