使用.reset()释放具有唯一所有权的boost :: shared_ptr

Zac*_*man 7 c++ boost memory-management sdl-image

我将一个object(TTF_Font)存储在shared_ptr从第三方API提供给我的对象中.我不能在对象上使用new或delete,因此shared_ptr也提供了一个"freeing"仿函数.

// 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() );
Run Code Online (Sandbox Code Playgroud)

如果,稍后,我需要明确释放此对象,这样做是正确的:

screenFont.reset();
Run Code Online (Sandbox Code Playgroud)

然后让screenFont(实际shared_ptr物体)自然地被摧毁?

Mic*_*urr 16

shared_ptr <> :: reset()会将引用计数减一.如果这导致计数降至零,则将释放shared_ptr <>指向的资源.

所以我认为你的答案是肯定会有效的.或者你可以简单地让screenFont变量因为掉出范围或其他什么而被破坏,如果那就是即将发生的事情.

要清楚的是,shared_ptr <>的正常用法是让它自然地被破坏,并且当它自然地降到零时它将处理refcount并释放资源.只有在shared_ptr <>被自然销毁之前需要释放共享资源的特定实例时,才需要reset().

  • 只是要清楚 - reset()不会释放持有的资源,除非它导致refcount下降到零 - 它不会强制refcount为零. (2认同)