std :: auto_ptr to std :: unique_ptr [英] std::auto_ptr to std::unique_ptr

查看:186
本文介绍了std :: auto_ptr to std :: unique_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新标准(和某些编译器中已有的部分),新类型 std :: unique_ptr 应该替代 std :: auto_ptr

With the new standard coming (and parts already available in some compilers), the new type std::unique_ptr is supposed to be a replacement for std::auto_ptr.

它们的使用完全重叠(所以我可以做一个全局查找/替换我的代码(不是我会这样做,但如果我做))或应该注意一些从阅读文档中看不出来的区别?

Does their usage exactly overlap (so I can do a global find/replace on my code (not that I would do this, but if I did)) or should I be aware of some differences that are not apparent from reading the documentation?

如果是直接替换(为什么给它一个新的名字),而不是只是改善 std :: auto_ptr

Also if it is a direct replacement (why give it a new name) rather than just improve the std::auto_ptr.

推荐答案

因为您可以复制 auto_ptr (已知结果),但只能移动 unique_ptr

You cannot do a global find/replace because you can copy an auto_ptr (with known consequences), but a unique_ptr can only be moved. Anything that looks like

std::auto_ptr<int> p(new int);
std::auto_ptr<int> p2 = p; 

必须至少成为这样

std::unique_ptr<int> p(new int);
std::unique_ptr<int> p2 = std::move(p);

至于其他差异, unique_ptr 数组正确(它将调用 delete [] ,而 auto_ptr 将尝试调用 delete

As for other differences, unique_ptr can handle arrays correctly (it will call delete[], while auto_ptr will attempt to call delete.

这篇关于std :: auto_ptr to std :: unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆