-
Considered bad design?
I have two classes, CSprite, and CSpritePalette... CSpritePalette contains bitmap information to animate a CSprite object. To instantiate a CSprite object you must pass a CSpritePalette pointer to it.
I choose this design instead of combining the CSprite and CSpritePalette into a single class because it's more efficient. If I have two sprites with the same animation on the screen, I only create one copy of the bitmaps.
Here's the potential problem. When the CSpritePalette pointer is passed to the CSprite object, the address is saved internally to continue loading bitmap data at a later time. If the CSpritePalette goes out of scope or gets deleted... well, goodbye program. I've read that it's bad design to save the address of a pointer for which the future of is unknown.
Anyway, does anyone see a problem with doing it this way? If i'm careful i'll keep the CSpritePalette in scope while using the CSprite object... but it still worries me. Any alternitives or safeguards I can implement to rid of this hazard?
-
Don't be silly. This is no different from other scoping issues. Just make sure you keep it in scope (or else dynamically allocate it)...
-
or have your class use smart pointers so that the last one with the reference to the object in memory will clean it up.
-
Example?
Or would this be incrementing some static variables? If so, then I think I get the idea.
-
Something like this, maybe?
Code:
class CSP {
CSP():ref_count(0){}
int ref_count;
void Attach(){
++ref_count;
}
void Detach(){
--ref_count;
if(ref_count <= 0)
//...delete this; // <--never tried that before! Not sure.
}
};
class CS {
CSP * CSP_ptr;
CS(CSP& address){
address.Attach();
CSP_ptr = &address;
//...
}
~CS(){ CSP_ptr->Detach(); }
};