也称为位拷贝、值拷贝,编译器只是将对象的值拷贝过来,编译器默认生成的构造函数和赋值运算符重载就是浅拷贝
一个类拥有资源(堆或者其他系统资源),这个类发生拷贝过程称为深拷贝,所以这个类的构造函数、赋值运算符以及析构函数必显式给出
写时拷贝在深浅拷贝的基础上增加了引用计数的方式来实现,用来记录资源使用者个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源
在拷贝自定义类型对象会涉及深拷贝,如果对象中涉及资源管理,只能用赋值,所以我们在拷贝时需要将内置类型和自定义类型区分,可以使用模板特化实现类型萃取
struct _true_type{}; //内置类型 struct _false_type{};//自定义类型 template <class T> struct _type_traits{ typedef _false_type is_POD_type; }; template <> struct _type_traits<int>{ typedef _true_type is_POD_type; }; template <> struct _type_traits<unsigned int>{ typedef _true_type is_POD_type; }; template <> struct _type_traits<char>{ typedef _true_type is_POD_type; }; template <> struct _type_traits<signed char>{ typedef _true_type is_POD_type; }; template <> struct _type_traits<unsigned char>{ typedef _true_type is_POD_type; }; template <> struct _type_traits<float>{ typedef _true_type is_POD_type; }; template <> struct _type_traits<double>{ typedef _true_type is_POD_type; }; template <class T> void _copy(T* dst, T*src, size_t n, _true_type){ memcpy(dst, src, n*sizeof(T)); } template <class T> void _copy(T* dst, T*src, size_t n, _false_type){ for (size_t i = 0; i < n; ++i){ dst[i] = src[i]; } } template <class T> void Copy(T* dst, T* src, size_t n){ _copy(dst, src, n, _type_traits<T>::is_POD_type()); }
