Learn C++学习笔记:第M章—移动语义和复制语义:为什么移动语义效率更高 & 怎么进行移动std::move

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 {
   
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值