智能指针在容器如std :: vector? [英] Smart pointers in container like std::vector?

查看:853
本文介绍了智能指针在容器如std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习智能指针( std :: auto_ptr ),只是阅读此处此处智能指针( std: :auto_ptr )不应该放在容器(即 std :: vector ),因为即使大多数编译器不会抱怨,它可能看起来是正确的。没有规则说智能指针不会被内部复制(例如通过向量类)并传递其所有权,则指针将变为NULL。



实际上,这种情况会多久发生一次?



我有向量的指针,如果在未来,我决定我有一个智能指针的向量什么我的选项?



我知道C ++ 0x和Boost库,但现在,我更喜欢坚持STL方法。

解决方案

/ em>不能对标准容器使用 std :: auto_ptr std :: auto_ptr 副本不是等价的,并且因为标准容器(和算法)被允许复制他们的元素,这将拧紧。也就是说,复制 std :: auto_ptr 的操作与对象的简单复制相比具有意义 other :意味着传输

您可以选择:


  1. Boost智能指针库。这可能是你最好的选择。

  2. 使用基本指针。这是快速和安全,只要你正确地管理指针。有时这可能是复杂的或困难的。例如,您必须自己处理(避免)双删除问题。

  3. 使用您自己的引用计数智能指针。那将是愚蠢的;请使用Boost智能指针。


I am learning about smart pointers (std::auto_ptr) and just read here and here that smart pointers (std::auto_ptr) should not be put in containers (i.e. std::vector) because even most compilers won't complain and it might seem correct. There is no rule that says smart pointers won't be copied internally (by vector class for example) and transfer its ownership, then the pointer will become NULL. In the end, everything will be screwed up.

In reality, how often does this happen?

Sometimes I have vectors of pointers and if in the future I decide I want to have a vector of smart pointers what would my options?

I am aware of C++0x and Boost libraries, but for now, I would prefer to stick to a STL approach.

解决方案

Yes, you really can't use std::auto_ptr with standard containers. std::auto_ptr copies aren't equivalent, and because standard containers (and algorithms) are allowed to copy their elements at will this screws things up. That is, the operation of copying a std::auto_ptr has a meaning other than a mere copy of an object: it means transferring an ownership.

Your options are:

  1. Use the Boost Smart Pointers library. This is arguably your best option.
  2. Use primitive pointers. This is fast and safe, so long as you manage the pointers properly. At times this can be complex or difficult. For example, you'll have to cope with (avoid) double-delete issues on your own.
  3. Use your own reference-counting smart pointer. That'd be silly; use a Boost Smart Pointer.

这篇关于智能指针在容器如std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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