Passing intrusive_ptr<SDL_Surface> to SDL_Surface* par

devilFish303 wrote:

Hi, I’m getting to grips with SDL at the moment (about 3/4 way through Lazy Foo’s tutorials). I’m also finding out about the use of smart pointers in exception safe code.

I am attempting to replace raw SDL_Surface pointers in my code with the boost library’s intrusive_ptr<SDL_Surface>. However, I’m not quite sure about the correct way to pass an intrusive_ptr<SDL_Surface> to a parameter of an SDL function that expects an SDL_Surface*.

The following code appears to work when I run my program (a very basic test that displays an image for 2 seconds then exits) but am I doing this the correct way?

SDL_Surface *screen = NULL;
intrusive_ptr<SDL_Surface> image = NULL;

void intrusive_ptr_add_ref( SDL_Surface* surface )

void intrusive_ptr_release( SDL_Surface* surface )
SDL_FreeSurface( surface );

intrusive_ptr<SDL_Surface> load_image( string filename )
//Load the image
intrusive_ptr<SDL_Surface> loadedImage( IMG_Load( filename.c_str() ), false );

//If there was an error loading the image
if( loadedImage == NULL )
	//TODO throw an exception

//Create an optimized image
intrusive_ptr<SDL_Surface> optimizedImage( SDL_DisplayFormat( loadedImage.get() ), false );

//Return the optimized image
return optimizedImage;


void apply_surface( int x, int y, const intrusive_ptr<SDL_Surface>& source, SDL_Surface* destination )
//Rectangle to hold the offsets
SDL_Rect offset;

//Get offsets
offset.x = x;
offset.y = y;

//Blit the surface
SDL_BlitSurface( source.get(), NULL, destination, &offset );


Also, I take it that you would not want to replace ?SDL_Surface* screen? with an intrusive_ptr as SDL_Quit() takes care of cleaning that up rather than SDL_FreeSurface?

That’s correct… and your code looks right to me!–
-Sam Lantinga, Founder and President, Galaxy Gameworks LLC

devilFish303 wrote:

Thanks for the feedback and very quick reply!

You’re welcome! :slight_smile: