对标准容器使用std :: unique_ptr [英] Using std::unique_ptr with standard containers
本文介绍了对标准容器使用std :: unique_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在寻找一种方法来做动态指针的安全向量和地图,当我意识到C ++ 11添加 unique_ptr
s。我调查了如何在Google上使用它们,但是未能成功查找详细信息。我需要知道的是以下内容:
- 指针和
unique_ptr
s除了自动内存收集? - 如何从向量或地图中删除
unique_ptr
?除了擦除迭代器,还有什么特殊的代码需要使用?
解决方案
b
unique_ptr
只是一个指针的包装,当 unique_ptr
被销毁时会删除指针。它没有开销(就像它替换的 auto_ptr
模板)。 unique_ptr
移动到
I've been looking for a way to do safe vectors and maps of dynamic pointers, when I realized C++11 adds unique_ptr
s. I looked into how to use them on Google, but have been unsuccessful in looking for details. What I need to know are the following:
- What, exactly, is different between pointers and
unique_ptr
s besides automatic memory collection? - How would I go about removing a
unique_ptr
from a vector or map? Is there any special code I have to use besides erasing the iterator?
解决方案
- Nothing. A
unique_ptr
is just a wrapper around a pointer, which deletes the pointer when theunique_ptr
is destroyed. It has no overhead (just like theauto_ptr
template it replaces). - Nope -- it will just work. The difficulty actually comes from inserting the pointer into the vector or map -- whereas you must move the
unique_ptr
into the container.
这篇关于对标准容器使用std :: unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文