A piece of code snippet:
std::unique_ptr<SDL_Renderer, decltype(&SDL_DestroyRenderer)>
cGraphics::Create_Renderer()
{
SDL_Renderer* temprenderer = SDL_CreateRenderer(m_Window.get(), -1, 0);
SDL_SetRenderDrawColor(temprenderer, 255, 255, 255, 0xff);
return std::unique_ptr<SDL_Renderer,
decltype(&SDL_DestroyRenderer)>(temprenderer,
SDL_DestroyRenderer);
}
What I know:
temprenderer
is of course destroyed when it goes out of scope;- a temporary
std::unique_ptr
is initialized with the raw pointer; - Although
std::unique_ptr
does not allow copy, it is OK to return by value; - Essentially the temporary
std::unique_ptr
is also destroyed when it goes out of scope; - We are now holding a copy of that temporary unique pointer
My question:
Why does the destruction of the raw pointer have no effect on the copy of the temporary unique pointer, which itself (the temporary unique pointer) is initialized with the raw pointer? In other words, what happens inside of that unique pointer that keeps the information from being lost?
My assumption is that the unique pointer also holds a raw pointer (e.g. .get()
), and when it is initiated by temprenderer
it copies the value of temprenderer
onto the raw pointer, and that information is again copied when the unique pointer goes out of scope.
OK now it sounds quite obvious after I thought it through, but I'd appreciate if someone can confirm this. I also found this:
A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment)
So maybe something extra happens when we return a unique_ptr
?