[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 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.

Create an account

Register a new account

• Forum Statistics

• Total Topics
628275
• Total Posts
2981740

• 10
• 11
• 17
• 10
• 9