How to intentionally delete a boost::shared_ptr?(如何有意删除 boost::shared_ptr?)
问题描述
我有很多 boost::shared_ptr<MyClass>
对象,并且在某些时候我有意要删除
其中一些以释放一些内存.(那时我知道我将不再需要指向的 MyClass
对象.)我该怎么做?
I have many boost::shared_ptr<MyClass>
objects, and at some point I intentionally want to delete
some of them to free some memory. (I know at that point that I will never need the pointed-to MyClass
objects anymore.) How can I do that?
我想你不能只用我用 get()
得到的原始指针调用 delete()
.
I guess you can't just call delete()
with the raw pointer that I get with get()
.
我在 boost::shared_ptr
中看到了一个函数 get_deleter(shared_ptr<T> const & p)
,但我不知道如何使用它,旁边还写着experimental.(我想我有 Boost 1.38.)
I've seen a function get_deleter(shared_ptr<T> const & p)
in boost::shared_ptr
, but I'm not sure how to use it, and also it says experimental right next to it. (I think I have Boost 1.38.)
也许只是为变量分配一个新的空 boost::shared_ptr
?那应该扔掉旧值并删除它.
Maybe just assign a new empty boost::shared_ptr
to the variable? That should throw away the old value and delete it.
推荐答案
你只管
ptr.reset();
请参阅shared_ptr 手册.相当于
shared_ptr<T>().swap(ptr)
您对每个不应再引用该对象的智能指针调用 reset
.最后一次这样的reset
(或任何其他导致引用计数降为零的操作,实际上)将导致使用删除器自动释放对象.
You call reset
on every smart pointer that should not reference the object anymore. The last such reset
(or any other action that causes the reference count drop to zero, actually) will cause the object to be free'ed using the deleter automatically.
也许您对智能指针编程技术感兴趣一>.它有一个关于延迟释放的条目.
Maybe you are interested in the Smart Pointer Programming Techniques. It has an entry about delayed deallocation.
这篇关于如何有意删除 boost::shared_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何有意删除 boost::shared_ptr?
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01