什么时候std :: weak_ptr有用? [英] When is std::weak_ptr useful?

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

问题描述

我开始学习C ++ 11的智能指针,我没有看到任何有用的使用 std :: weak_ptr 。有人可以告诉我 std :: weak_ptr 是有用还是必要?

I started studying smart pointers of C++11 and I don't see any useful use of std::weak_ptr. Can someone tell me when std::weak_ptr is useful/necessary?

推荐答案

p>一个很好的例子就是缓存。

A good example would be a cache.

对于最近访问的对象,你想把它们保存在内存中,所以你拥有一个强大的指针。定期地,您扫描缓存并确定哪些对象最近未被访问。

For recently accessed objects, you want to keep them in memory, so you hold a strong pointer to them. Periodically, you scan the cache and decide which objects have not been accessed recently. You don't need to keep those in memory, so you get rid of the strong pointer.

但是如果该对象正在使用,而其他一些代码却拥有强大的指针呢?如果缓存删除其唯一的指针指向对象,它永远不会再找到它。因此,缓存保持一个弱指针,如果它们恰好留在内存中,它需要找到的对象。

But what if that object is in use and some other code holds a strong pointer to it? If the cache gets rid of its only pointer to the object, it can never find it again. So the cache keeps a weak pointer to objects that it needs to find if they happen to stay in memory.

这是一个弱指针 - 它允许你找到一个对象,如果它仍然在周围,但不保持它,如果没有别的需要它。

This is exactly what a weak pointer does -- it allows you to locate an object if it's still around, but doesn't keep it around if nothing else needs it.

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

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