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

被折叠的 条评论
为什么被折叠?



