-
Dynamic memory managment
What is the best way to use new/delete in programs?? When declaring a class, should everything be declared as pointers and made dynamic or is there advantages to not doing this? At the moment I know how to declare and use dynamic variables, but I dont know if there is a reason I shouldnt do so.
TIA
-
Why would you force yourself to deal with all the extra syntax if you don't have to? Also, the amount of memory you can use is limited; so you can't just write a large program with all dynamically allocated memory.
-
No reason not to. Free's up space on program stack. Passing less information back and forth between functions so may be a little quicker (depending how big and how many objects there are), etc. If you feel comfortable doing it, do it.
-
golfinguy4: Also, the amount of memory you can use is limited; so you can't just write a large program with all dynamically allocated memory.
why not?
u think staticmemory isn't limited?
-
Personally, I don't think it's worth it. The performance increase would not be that great. My theory is if it isn't broken, don't fix it.
-
I say: If you know how to handle pointers and dynamically allocated memory, use it. If you don't know how to handle it, you can screw things up bad. But if you don't know how to use it, you should learn nontheless.
Now to your question of when to use it:
You classes should have pointers to other classes. They should not hold the object directly. In a time critical loop, you should try to minimize the use of new/delete. If a section is time critical, allocate all you can before the section, and delete all after that section. Allocation in a timecritical loop is a bad thing. What more advantages is there to have pointers? If you call a function, with the class as param, or a pointer to the class as param, which will be faster? the pointer of cause. The pointer is 4 - 8 byte long, the class could be 100 byte long or more. pushing 4 bytes to the stack compared to 100 bytes is a big difference. Also, you will have 100 bytes on 2 places. Where it was declared, and on the call stack... so you save memory by the use of pointers. So event if the class isn't dynamic in the first place, always make functions that take this class take pointers...
/dave
-
dynamomemo is closer than static
-