weak_ptr,make_shared和内存释放 [英] weak_ptr, make_shared and memory deallocation

查看:603
本文介绍了weak_ptr,make_shared和内存释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

shared_ptr的控制块在存在至少一个weak_ptr时保持活动状态.如果共享指针是用make_shared创建的,则意味着该对象的整个内存将保持分配状态. (对象本身已被适当地破坏,但是由于对象的控制块和内存是像make_shared一样分配在一个块中的,因此只能将它们一起释放.)

A control block of a shared_ptr is kept alive while there is at least one weak_ptr present. If the shared pointer was created with make_shared that implies that the whole memory of the object is kept allocated. (The object itself is properly destructed, but since the control block and the memory for the object were allocated in one chunk, as make_shared does, they can only be deallocated together.)

我的理解正确吗?

例如,著名的缓存示例" .对象的内存将永远保持分配状态.

It seems that this behaviour represents a problem, for example in the famous "cache example". The memory for the objects will be kept allocated forever.

在任何实际情况下都存在问题吗?在这种情况下(大对象并打算使用weak_ptr),是否应该使用构造函数创建shared_ptr?

It it a problem in any practical situations? Shall the shared_ptr be created using a constructor in such a situation (large object and intent to use weak_ptrs)?

推荐答案

我的理解正确吗?

Is my understanding correct?

是的.如果weak_ptr的寿命大大超过了(大)对象,并且您的内存不足,则最好避免使用make_shared.

Yes. If your weak_ptrs significantly outlive the (large) object and you are tight on memory, it may be beneficial to avoid make_shared.

但是,这里的大"是由sizeof度量的,并且许多概念上的大"对象(例如,除std::array以外的大多数标准容器)都按该度量很小,因为它们分配了额外的内存来存储它们的内容,一旦对象被销毁,这些内容将被释放.

However, "large" here is measured by sizeof, and many conceptually "large" objects (for example, most standard containers, except std::array) are quite small by that metric, because they allocate additional memory to store their contents, which will be freed as soon as the object is destroyed.

这篇关于weak_ptr,make_shared和内存释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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