C ++ 11智能指针策略 [英] C++11 Smart Pointer Policies

查看:149
本文介绍了C ++ 11智能指针策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,在当前C ++ 11规范中,应该使用:





  • std :: shared_ptr<> 仅当非循环结构中有多个所有者时

  • std :: weak_ptr<>

  • 当引用不足时,将原始指针作为内存句柄(无所有权)



所以我的问题是:


  1. 这些政策是否足够或有其他政策

  2. scoped_ptr<> auto_ptr<> 有效过时?


解决方案


Are scoped_ptr<> and auto_ptr< ;>有效废弃?


auto_ptr 所以有你的答案。 scoped_ptr 在C ++ 11中不存在,从来没有。使用 boost :: scoped_ptr 的主要原因是确保所有权永远不会被转移(除非你欺骗,当然)。再次,如果您使用 unique_ptr ,则只有使用 std :: move 或类似结构才能转移所有权。或者,Howard指出,只要使它成为 const std :: unique_ptr



你是否想要额外的保险。此外 boost :: scoped_ptr 没有删除程序支持。因此 unique_ptr 可以玩 boost :: scoped_ptr 不能。



std :: weak_ptr&我不能说我同意这项政策。当对象可能想要与其他对象通信时,应使用 weak_ptr ,但它不会拥有。这意味着它可以随时删除,并且 weak_ptr 的持有者需要能够在任何时候尝试与之交谈时处理该删除。



破裂循环是 weak_ptr 的使用中的 它不应该是唯一的时间被使用。


As I understand it, in the current specification of C++11, one should use:

  • std::unique_ptr<> for one owner (most of the time)
  • std::shared_ptr<> only when there are multiple owners in acyclic structure
  • std::weak_ptr<> sparingly only when there are cycles that need to be broken
  • A raw pointer as a handle to memory (no ownership) when a reference would not suffice

So my questions are:

  1. Are these policies sufficient or are there additional policies that I should be aware of?
  2. Are scoped_ptr<> and auto_ptr<> effectively obsolete?

解决方案

Are scoped_ptr<> and auto_ptr<> effectively obsolete?

auto_ptr is deprecated in C++11, so there's your answer. scoped_ptr doesn't exist in C++11 and never did. The main reason to use boost::scoped_ptr is to ensure that ownership is never transferred (unless you cheat, of course). Then again, if you use unique_ptr, ownership can only be transferred if you use std::move or similar constructs. Or, as Howard points out, just make it a const std::unique_ptr.

So it's really up to you whether you want that extra bit of insurance. Also boost::scoped_ptr doesn't have deleter support. So unique_ptr can play tricks that boost::scoped_ptr cannot.

std::weak_ptr<> sparingly only when there are cycles that need to be broken

I can't say I agree with this policy necessarily. A weak_ptr should be used when an object may want to talk to something else, but it doesn't own that something else. Which means that it can be deleted at any time, and the holder of the weak_ptr needs to be able to handle that deletion anytime it tries to talk to it.

Breaking cycles is one of the uses of weak_ptr; it should not be the only time it is used.

这篇关于C ++ 11智能指针策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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