unique_ptr优于auto_ptr的原因

本文探讨了unique_ptr优于auto_ptr的两个主要原因。首先,unique_ptr在编译阶段就防止了错误的赋值操作,避免运行时错误。其次,unique_ptr支持new[],并正确使用delete[],而auto_ptr不支持。此外,unique_ptr可以与nullptr比较,且可通过std::move()转移所有权。

第一个原因

请看一段使用auto_ptr的代码:

//使用auto_ptr不当的后果
int main()
{
    auto_ptr<int> aptr1(new int);
    auto_ptr<int> aptr2(new int);
    *aptr1 = 3;
    aptr2 = aptr1;
    cout << *aptr2 << endl;
    cout << *aptr1 << endl;        //运行阶段错误,aptr1已移交控制权
    cin.get();
}  

aptr1将控制权移交给aptr2,然而编译阶段并不认为输出*aptr1是错误的,

然而编译阶段错误总比运行阶段错误要好


再看一段使用unique_ptr的代码:

int main()
{
    unique_ptr<int> uptr1(new int);
    unique_ptr<int> uptr2(new int);
    *uptr1 = 7;
    uptr2 = uptr1;                    //编译阶段错误,不允许这种赋值
    cin.get();
}  

unique_ptr的指针不允许上述赋值,因为uptr1之后的操作可能会导致运行阶段失败
unique_ptr只允许右值赋值,因为右值会立即过期,不会有意想不到的操作

这也是unique_ptr优于auto_ptr之处


*ps : 顺便一提,auto_ptr类没有重载==去判断是否是nullptr,而unique_ptr可以与nullptr进行比较

*如果想将unique_ptr赋值给其他unique_ptr,可以使用std::move()函数



第二个原因

  • auto_ptr只能和new使用,不能与new[]一起使用,因为他只有delete而**没有**delete[]
  • unique_ptr可以与new[]使用,因为他有delete[]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值