当我意识到 C++11 添加了 unique_ptr
时,我一直在寻找一种方法来实现动态指针的安全向量和映射。我在谷歌上研究了如何使用它们,但没有成功地找到细节。我需要知道以下内容:
- 除了自动内存收集之外,指针和 unique_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?
发布评论
评论(2)
unique_ptr
只是指针的包装器,当unique_ptr
被销毁时,它会删除指针。它没有任何开销(就像它所替换的 auto_ptr 模板一样)。unique_ptr
移动到容器中。
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).unique_ptr
into the container.不同之处在于 unique_ptr 遵循移动语义。此外,顾名思义,您无法复制它。
删除
std::vector的元素>
将有效删除指针所指向的任何内容。The difference is that unique_ptr obeys move semantics. Further, as the name suggests, you can't make copies of it.
Erasing an element of
std::vector<std::unique_ptr<T> >
will effectively delete whatever that pointer pointed at.