对标准容器使用std :: unique_ptr [英] Using std::unique_ptr with standard containers

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

问题描述

我一直在寻找一种方法来做动态指针的安全向量和地图,当我意识到C ++ 11添加 unique_ptr s。我调查了如何在Google上使用它们,但是未能成功查找详细信息。我需要知道的是以下内容:


  1. 指针和 unique_ptr s除了自动内存收集?

  2. 如何从向量或地图中删除 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_ptrs. 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:

    1. What, exactly, is different between pointers and unique_ptrs besides automatic memory collection?
    2. 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?

    解决方案

    1. Nothing. A unique_ptr is just a wrapper around a pointer, which deletes the pointer when the unique_ptr is destroyed. It has no overhead (just like the auto_ptr template it replaces).
    2. 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屋!

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