Sign in to follow this  
sheep19

[SDL] assigning SDL_Surface

Recommended Posts

Hi. I using SDL to make Pong. I wrote my own class for the surface so I won't need to use SDL_FreeSurface, but it will be called by itself in the destructor.
#ifndef MYSURFACE_H
#define MYSURFACE_H

#include <SDL/SDL.h>

class mySurface
{
public:
	mySurface();
	~mySurface();

	mySurface& operator =(mySurface &surf);
	mySurface& operator =(SDL_Surface *surf);

private:
	SDL_Surface *surface;
};

#endif // MYSURFACE_H

#include "mySurface.h"

mySurface::mySurface(): surface(NULL)
{
}

mySurface::~mySurface()
{
	SDL_FreeSurface(surface);
}

mySurface& mySurface::operator =(mySurface &surf)
{
	if(&surf == this) // if we aren't assigning to itself
	{
		if(surface) // if surface isn't NULL
			SDL_FreeSurface(surface);

		surface = surf.surface;
	}
	return *this;
}

mySurface& mySurface::operator =(SDL_Surface *surf)
{
	if(surface)
		SDL_FreeSurface(surface);
	
	surface = surf;

	return *this;
}

Something tells me that it's not correct to assing an SDL_Surface to another. Am I correct? Is there a function by SDL to do that? Thanks in advance.

Share this post


Link to post
Share on other sites
Your assignment operators contain duplicate code and the check for self-assignment is incorrect (== should be !=). You also don't have a copy constructor (and the default one has different semantics than your assignment operators, which is a bad idea.)

Also, I'm not sure if this behavior is useful or desirable. A better alternative would be to either disallow copy/assignment or use reference counting. If you want the latter, you might as well use boost::shared_ptr. It will also release your surfaces automatically (it can accept a custom deleter) so you won't need this class at all.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this