do std :: weak_ptrs会影响std :: make_shared分配的内存何时被释放? [英] Do std::weak_ptrs affect when the memory allocated by std::make_shared is deallocated?

查看:918
本文介绍了do std :: weak_ptrs会影响std :: make_shared分配的内存何时被释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我调用 std :: make_shared< T> (而不是仅仅分配一个 shared_ptr< T> ),那么我预计引用计数将分配在内存中的T实例,出于性能原因。

If I call std::make_shared<T> (rather than just allocating a shared_ptr<T> explicitly) then I expect the reference count to be allocated in memory alongside the instance of T, for performance reasons. All well and good.

但如果我有 weak_ptr 实例引用同一个对象,那么他们需要访问

But if I have weak_ptr instances referencing the same object, presumably they will need access to that reference count, to know whether the object still exists.

因此,当T的实例的最后一个shared_ptr被销毁时,对系统的初步理解将意味着,它不能释放T所存储的内存,因为weak_ptrs仍然需要访问该计数。

So, when the last shared_ptr to the instance of T is destroyed, a naive understanding of the system would imply that it cannot deallocate the memory that T is stored in, because weak_ptrs still require access to that count.

看起来像是有一个单独的弱引用计数器,并且在理论上可以与T的实例分开保持,使得T可以被销毁并且在弱引用仍然存在时释放存储器。但是我们又回到了两个单独的分配,阻止了 make_shared 的好处。

It seems like there is a separate weak reference counter and in theory that could be held separately from the instance of T, so that the T can be destroyed and the memory deallocated while weak references still exist. But then we're back to having 2 separate allocations, thwarting the benefits of make_shared.

误解这里的东西。

推荐答案

如果使用 make_shared ,如果实现对对象和引用计数使用单个分配,那么该分配不能被释放,直到所有引用(强和弱)已被释放。

If you use make_shared and if the implementation uses a single allocation for both the object and the reference counts, then that allocation cannot be freed until all references (both strong and weak) have been released.

然而,对象将在所有强引用释放后被销毁(无论是否还存在弱引用)。

However, the object will be destroyed after all strong references have been released (regardless of whether there are still weak references).

这篇关于do std :: weak_ptrs会影响std :: make_shared分配的内存何时被释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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