Using .reset() to free a boost::shared_ptr with sole ownership

21,396

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.

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.

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.

Share:
21,396
Shoaib
Author by

Shoaib

I'm a front end engineer located in the Bay Area. I'm passionate about web technologies and the art of programming. I also like: Photography NES games (Mega Man) Wright's Pink Popcorn

Updated on July 09, 2022

Comments

  • Shoaib
    Shoaib almost 2 years

    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();
    

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

  • Shoaib
    Shoaib over 15 years
    Thanks for the response. In my case, I have to explicitly free it before another resource, and this was the only way I found to do that.
  • Michael Burr
    Michael Burr over 15 years
    Just to be clear - reset() will not free the held resource unless it results in the refcount dropping to zero - it does not force the refcount to zero.
  • Shoaib
    Shoaib over 15 years
    Thanks. That is what I was doing initially. I found a bug related to another resource being freed before my font resource and tried to solve it by the above method. Although the bug was unrelated to the functor, I kept it because I'm handling other resources with the same pattern.