shared_ptr的:什么是它的用途 [英] shared_ptr: what's it used for

查看:461
本文介绍了shared_ptr的:什么是它的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了很多使用boost :: scoped_ptr的的在我的code,这是伟大的,但我目前正在与使用shared_ptr的所有的地方软件的工作,我想知道如果我失去了一些东西。

I make a lot of use of boost::scoped_ptr in my code and it is great but I'm currently working with software that uses shared_ptr all over the place and I'm wondering if I'm missing something.

AFAIK如果不同的线程将要访问相同的数据和不知道什么样的顺序线程将要结束(与shared_ptr的确保存在对象,直到最后一个线程已经与完成一个shared_ptr才有用它)。

AFAIK a shared_ptr is only useful if different threads are going to be accessing the same data and you don't know what order the threads are going to finish (with the shared_ptr ensuring that the object exists until the last thread has finished with it).

是否有其他使用案例?

推荐答案

线程是这里无关紧要。什么是相关的是,是否可以很容易地指定一个点,在该对象不再使用。

Threads are irrelevant here. What's relevant is whether it's easy to specify a point at which the object is no longer of use.

假设几个不同的对象要使用相同的对象。这可能是数据包,或者输入/输出,或者一些几何对象,或什么的。你想共享对象被删除之前,在所有的使用对象被删除,而不是一个时钟周期。而不是找出哪些所属对象将不得不寿命最长(如果你通过用户交互更改程序,或者可以改变),你可以用一个shared_ptr来强制这一行为。

Suppose several different objects want to use the same object. It might be a pack of data, or for input/output, or some geometric object, or whatever. You want the shared object to be deleted after all of the using objects are deleted, and not a clock cycle before. Rather than figure out which owning object is going to have the longest lifespan (and that can change if you change the program, or perhaps through user interaction), you can use a shared_ptr to force this behavior.

没关系的使用对象是否在相同或不同的线程。对象可以有未predictable寿命,即使他们都在同一个线程。

It doesn't matter whether the using objects are in the same or different threads. Objects can have unpredictable lifetimes even if they're all in the same thread.

这篇关于shared_ptr的:什么是它的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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