Home > Software design >  How to Manually call a Destructor on a Smart Pointer?
How to Manually call a Destructor on a Smart Pointer?

Time:12-13

I have a shared_ptr for an SDL_Texture in a game I'm making. I want to use a shared pointer to be able to use the same texture on multiple objects without leaking any memory. I have the shared pointer return from a method which is

std::shared_ptr<SDL_Texture> RenderWindow::loadTexture(const char *filePath) {

    return std::shared_ptr<SDL_Texture>(IMG_LoadTexture(renderer, filePath),
            SDL_DestroyTexture);
}

However, when I'm done using the texture in the game, I want to be able to manually call it's destructor, which is SDL_DestroyTexture however that doesn't get called when I need it to and it takes up a lot of memory. Is there any way of telling it to call its destructor when I want it to?

CodePudding user response:

You can release the ownership of the object by calling reset() on the shared_ptr. If that is the last one holding the pointer, the shared_ptr's deleter member will be used to destroy the object.

https://en.cppreference.com/w/cpp/memory/shared_ptr/reset

  • Related