开发者

when returning by address, doesnt this go out of scope? ( SDL)

this is a code example from lazyfoo's SDL tutorials.

SDL_Surface *load_image( std::string filename ) { 

//Temporary storage for the ima开发者_如何学Pythonge that's loaded 
SDL_Surface* loadedImage = NULL; 
//The optimized image that will be used 
SDL_Surface* optimizedImage = NULL; 

//Load the image 
loadedImage = SDL_LoadBMP( filename.c_str() ); 


//If nothing went wrong in loading the image 
if( loadedImage != NULL ) { 
    //Create an optimized image 
    optimizedImage = SDL_DisplayFormat( loadedImage ); 
    //Free the old image 
    SDL_FreeSurface( loadedImage ); 
} 

//Return the optimized image 
return optimizedImage; 
} 

Here shouldn't optimizedImage go out of scope when it returns? seeing as it is local.


It does, but not the allocated memory pointed by it. It is a merely 4 byte pointer variable, the only thing needed from it is to retain its value.

The value is the address. The address is something allocated in manually controlled fashion, and deallocating it requires calling functions the compiler does not know about.


optimizedImage is in the function's stack, so it goes out of scope after the function returns. The object it points to is in the heap, so it remains there until no other pointer is referring to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜