Object obj;
// keep it there and initialize and use as needed
Object *obj;
// object is needed
if(obj)
throw ObjectIsntDeleted();
obj = new Object();
delete obj;
should i allocate the memory once?
if i need a single object repeatedly throughout a program should i allocate and re-allocate or should i just create it once?
i.e
which is better and why? (ignoring the dangers of pointers)
It really depends on what you are using it for. I feel like thats a cheesy answer, but the question is kind of vague... Do you have any specific example that you are considering?
If its some kind of a managing class, I would just instantiate it once and keep it throughout the program lifetime. Many other things I would just create when needed
If its some kind of a managing class, I would just instantiate it once and keep it throughout the program lifetime. Many other things I would just create when needed
class AnimatedSprite{ public: void PlayAnimation(const string &animname , int n); private: struct PlayingAnimation { AnimationIterator anim_it; bool isplaying; int play_count; }playing;};
when i play the animation i set the bool and initialize anim_it
OR
class AnimatedSprite{ public: void PlayAnimation(const string &animname , int n); private: struct PlayingAnimation { AnimationIterator *anim_it; int play_count; }playing;};
use the anim_it as the bool and create and allocate as is needed. Which is a better solution?
ok thanks. it was kinda a cpu vs memory issue (since there are a lot of these kinds of objects around). I know its being kinda nitty gritty but I thought I might be losing out by not asking.
I'd also say go with the first solution. The second one is just too error prone - if you're facing performance issues later on, go with object pooling (which can be easily equipped to existing classes as seen in the Loki Library, but I don't think that would ever be the case here, stack allocation is blindingly fast.
-Markus-
-Markus-
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement