如何有意删除 boost::shared_ptr?

How to intentionally delete a boost::shared_ptr?(如何有意删除 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?

基础教程推荐