From 5a281cf661ac25f7db8461c31159a31a4091a3f4 Mon Sep 17 00:00:00 2001 From: Maarten ter Huurne Date: Sun, 10 Aug 2014 03:18:32 +0200 Subject: [PATCH] Implement the standard set of copy and move operations for Surface --- src/surface.cpp | 33 ++++++++++++++++++++++++++++----- src/surface.h | 8 +++++++- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/surface.cpp b/src/surface.cpp index ba96134..bc7ccca 100644 --- a/src/surface.cpp +++ b/src/surface.cpp @@ -28,6 +28,7 @@ #include #include #include +#include using namespace std; @@ -94,22 +95,44 @@ Surface::Surface(SDL_Surface *raw_, bool freeWhenDone_) { } -Surface::Surface(Surface *s) { - raw = SDL_ConvertSurface(s->raw, s->raw->format, SDL_SWSURFACE); +Surface::Surface(Surface const& other) + : Surface(SDL_ConvertSurface( + other.raw, other.raw->format, SDL_SWSURFACE), true) +{ // Note: A bug in SDL_ConvertSurface() leaves the per-surface alpha // undefined when converting from RGBA to RGBA. This can cause // problems if the surface is later converted to a format without // an alpha channel, such as the display format. - raw->format->alpha = s->raw->format->alpha; - freeWhenDone = true; + raw->format->alpha = other.raw->format->alpha; } -Surface::~Surface() { +Surface::Surface(Surface&& other) + : raw(other.raw) + , freeWhenDone(other.freeWhenDone) +{ + other.raw = nullptr; + other.freeWhenDone = false; +} + +Surface::~Surface() +{ if (freeWhenDone) { SDL_FreeSurface(raw); } } +Surface& Surface::operator=(Surface other) +{ + swap(other); + return *this; +} + +void Surface::swap(Surface& other) +{ + std::swap(raw, other.raw); + std::swap(freeWhenDone, other.freeWhenDone); +} + void Surface::convertToDisplayFormat() { SDL_Surface *newSurface = SDL_DisplayFormat(raw); if (newSurface) { diff --git a/src/surface.h b/src/surface.h index 32521f8..aa643d7 100644 --- a/src/surface.h +++ b/src/surface.h @@ -52,8 +52,14 @@ public: static Surface *loadImage(const std::string &img, const std::string &skin="", bool loadAlpha=true); - Surface(Surface *s); + // TODO: Remove this once naked Surface pointers are no longer in use. + Surface(Surface *other) : Surface(*other) {} + + Surface(Surface const& other); + Surface(Surface&& other); ~Surface(); + Surface& operator=(Surface other); + void swap(Surface& other); /** Converts the underlying surface to the same pixel format as the frame * buffer, for faster blitting. This removes the alpha channel if the