2010-06-21 39 views
1

這是lazyfoo的SDL教程的代碼示例。當通過地址返回時,這不會超出範圍嗎? (SDL)

SDL_Surface *load_image(std::string filename) { 

//Temporary storage for the image 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; 
} 

這裏不應該優化圖像當它返回時超出範圍?因爲它是本地的。

回答

2

它確實,但不是它指定的分配內存。它只是一個4字節的指針變量,唯一需要的就是保留它的值。

該值是地址。地址是以手動方式分配的,並且釋放它需要編譯器不知道的調用函數。

0

optimizeImage位於函數的堆棧中,因此在函數返回後超出範圍。它指向的對象在堆中,所以它一直存在,直到沒有其他指針指向它爲止。