用于资源管理的C ++ shared_ptr与unique_ptr [英] C++ shared_ptr vs. unique_ptr for resource management

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

问题描述

我一直在考虑使用unique_ptr vs shared_ptr vs own_solution.我不赞成后者,因为我几乎肯定会弄错,但是unique_ptrshared_ptr都存在问题,因为它们都不能准确地捕捉我想要的东西.我想创建一个明确拥有资源的资源管理器,但是我希望该资源管理器也分发对该资源的引用.

I've been mulling over use of unique_ptr vs shared_ptr vs own_solution. I've discounted the latter as I'll almost certainly get it wrong, but I have a problem with both unique_ptr and shared_ptr in that neither captures precisely what I want. I want to create a resource manager which explicitly owns a resource, however I'd like the resource manager to also hand out references to the resource.

如果我在资源管理器中使用unique_ptr并分发原始指针,则它们有可能会在其他地方转义(尽管这与我认为的合同"类相反).如果我使用shared_ptr并分发weak_ptr,则不会阻止调用者将weak_ptr转换为shared_ptr并将其存储,从而有可能造成一个循环或更糟的情况,即资源寿命超过资源的寿命经理.因此,我想我要寻找的是可延期的weak_ptr,它无法转换为shared_ptr.

If I use unique_ptr in the resource manager and hand out raw pointers there's the possibility they could escape elsewhere (though this would be against the class "contract" I suppose). If I use shared_ptr and hand out weak_ptr, there's nothing stopping a caller from converting the weak_ptr to a shared_ptr and storing that, thereby potentially creating a cycle or worse, a resource living beyond the lifetime of the resource manager. So I suppose what I'm looking for is a deferencable weak_ptr that cannot be converted into a shared_ptr.

还是我只是想通过代码中一些措辞强烈的注释来执行合同?

Or am I just looking to enforce the contract with some strongly worded comments in the code?

感谢您对此的任何想法.

Thanks for any thoughts you might have on this.

推荐答案

当拥有 owning 指针时,像shared_ptrunique_ptr这样的智能指针是很好的工具.
但是对于非所有指针,即观察指针,使用原始指针就可以了.

Smart pointers like shared_ptr and unique_ptr are a good tools when you have owning pointers.
But for non-owning pointers, i.e. observing pointers, using a raw pointer is just fine.

在您的设计中,我认为资源管理器是资源的唯一所有者",因此您可以在资源管理器内部简单地使用某种形式的智能指针 .例如,如果您的Resource类被设计为可正确存储在std::vector中,则资源管理器可以将std::vector<std::unique_ptr<Resource>>作为数据成员,甚至可以使用更简单的std::vector<Resource>.

In your design, I think the resource manager is the only "owner" of the resources, so you could simply have some form of smart pointer inside the resource manager. For example, the resource manager can have a std::vector<std::unique_ptr<Resource>> as a data member, or even a simpler std::vector<Resource> if your Resource class is designed to be correctly storable in a std::vector.

然后,资源管理器可以仅向外部提供非所有者的观察指针,原始指针(或C ++引用)在这种情况下就可以了.

Then, the resource manager can give to the outside just non-owning observing pointers, and raw pointers (or C++ references) are fine for this case.

当然,重要的是资源管理器的生存期必须超过资源客户端"的生存期.

Of course, it's important that the lifetime of the resource manager exceeds that of the "resource clients".

这篇关于用于资源管理的C ++ shared_ptr与unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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