Jump to content
  • Advertisement
  • entries
  • comments
  • views

Copy on write, it's not just for strings anymore!

Sign in to follow this  


I Finally implemented something in my game class library that I should've implemented quite a long time ago. . .

Copy-On-Write bitmap objects.

The bitmap object is one of the cornerstones of the whole library. It encapsulates a bitmap's data (in my case, an SDL_SURFACE structure) and has functions to do blitting and such.
Problem is that bitmaps are pretty heavy objects, and doing something like the following can be costly.

class DialogBox

DialogBox(const Bitmap &rBackground) : MyBackground(rBackground) { }
Bitmap MyBackground;

void Main()
DialogBox MyDialog(Bitmap('back.png'));

With a traditional bitmap object, the code in Main() is pretty costly, as it forces a bitmap to copy all of its data over from the temporary object into the MyBackground member. With a copy-on-write bitmap, though, bitmaps created with a copy-constructor or operator= all point to the same data unless they're written to. In the case above, the cost of copying the bitmap is reduced to just incrementing (when the bitmap is copied), then decrementing (when the temporary object dies), a reference-count. This is much
cheaper than creating, copying, and deleting all bitmap data from the temporary object.

It also allows me to implement some stuff the Right Way --the Sprite
object, for example. My old Sprite object simply pointed to an 'archive' bitmap, as it would be very
wasteful for 40 identical space-invader sprites to have 40 pieces of identical bitmap data. With copy-on-write
bitmaps, though, I can derive a Sprite object from Bitmap, and invader Sprites created with a copy-constructor
all point to the same data. If I ever did want to write to a Sprite object's data (like if I wanted to draw some
damage on a space invader) I can do that now. As I write to an invader, it'll copy itself so it doesn't cause all
the other invaders to be written to.
Sign in to follow this  


Recommended Comments

There are no comments to display.

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
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!