1、移动语义效率更高
前面讲到,之所以采用移动,原因①是为了避免多个智能指针指向同一个内存,导致的释放问题。除了这个优点之外,还有原因②移动语义还比复制语义多一个优点,效率更高。
具体来看一个例子:
template<class T>
class Auto_ptr3
{
T* m_ptr;
public:
Auto_ptr3(T* ptr = nullptr):m_ptr(ptr){
}
~Auto_ptr3(){
delete m_ptr;}
// 复制语义,进行深拷贝,避免重新释放内存
Auto_ptr3(const Auto_ptr3& a){
m_ptr = new T;
*m_ptr = *a.m_ptr;
}
// 复制语义,同上
Auto_ptr3& operator=(const Auto_ptr3& a){
// Self-assignment detection
if (&a == this) return *this;
// Release any resource we're holding
delete m_ptr;
// Copy the resource
m_ptr = new T;
*m_ptr = *a.m_ptr;
return *this;
}
T& operator*() const {