使用.reset段()来释放一个boost :: shared_ptr的有独资 [英] Using .reset() to free a boost::shared_ptr with sole ownership

查看:1030
本文介绍了使用.reset段()来释放一个boost :: shared_ptr的有独资的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在存储对象( TTF_Font )一个的shared_ptr 是从三阶提供给我党的API。我不能使用新的或删除的对象,因此的shared_ptr 还提供了释放仿函数。

I'm storing an object (TTF_Font) in a shared_ptr that is provided to me from a third-party API. I cannot use new or delete on the object, so the shared_ptr is also provided a "freeing" functor.

// Functor
struct CloseFont
{
    void operator()(TTF_Font* font) const
    {
        if(font != NULL) {
            TTF_CloseFont(font);
        }
    }
};

boost::shared_ptr<TTF_Font> screenFont;

screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() );

如果,以后,我需要明确地释放该对象是正确的做到这一点:

If, later, I need to explicitly free this object is it correct to do this:

screenFont.reset();

然后让 screenFont (实际的shared_ptr )对象很自然地被破坏?

And then let screenFont (the actual shared_ptr object) be destroyed naturally?

推荐答案

&的shared_ptr LT;> ::复位()将下降1引用计数。如果在计数下降到零结果,资源所指向的shared_ptr&下;>将被释放

shared_ptr<>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared_ptr<> will be freed.

所以,我认为答案对你来说,是将工作。或者,你可以简单地让screenFont变量遭到破坏,由于辍学的范围或什么的,如果这是什么即将发生。

So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen.

需要明确的是,shared_ptr的&LT的正常使用;>是让它自然的破坏,当它降到零,自然会处理引用计数和释放资源。复位()只需要如果你需要的shared_ptr&LT之前释放的共享资源的特定实例;>将破坏自然

To be clear, the normal usage of shared_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr<> would be naturally destructed.

这篇关于使用.reset段()来释放一个boost :: shared_ptr的有独资的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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