shared_ptr:它用于什么 [英] shared_ptr: what's it used for

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

问题描述

我在我的代码中使用了很多boost :: scoped_ptr,它是伟大的,但我目前使用的软件,使用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 a 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.

无论使用对象是在相同或不同的线程中。对象可能具有不可预测的生命周期,即使他们都在同一个线程。

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天全站免登陆