|
-
July 4th, 2009, 01:02 AM
#1
Memory Allocation Strategies in c++ :
hi,
i am trying to find a good design pattern to handle memory allocation of my objects in c++.
good = no errors , fastest.
I will post all designs i have thought.
For example we will use the following:
class creature : represents a monster than when killed it must be deleted.
class creatureManager : stores creatures / takes care of their destruction.
1) use of shared_ptr : (works without bugs)
c++ will call delete thus making c++ slower than java.
a) because delete and new will be called very often for small objects, whereas in java you do garbage collection when you "need" to, so you do garbage collection in big part of the memory.
b) because java does garbage collection in a seperate tread = no cost because of multicore cpus.
we chose c++ instead of java because of its speed, so why lose that benefit.
2) creatureManager has full ownership of its objects. with the following way.
a) creatures that are added to the creatureManager, now will belong only to
creatureManager (passByReference).
b) the class will be responsible for deleting the corresponding object when needed,
e.g when a unit dies.
However that means that the destruction phase cant be called at any time
e.g someone calls get(...) to get a creature (for temporal use e.g 1 frame), but at the same
time the creature dies, so we have an error we use an address that doesnt exist.
This dictates the following : (if there is an alternative please say)
c) the destruction phase will be called after the simulation phase (where creatures attacks,
gets killed, etc ...).
so the game loop will be :
while(true)
{
simulate();
destruction_phase();
show_graphics();
}
d)We cant use array/vector since deletition of objects will force it to resize(slow).
We cant use a linked list because iterating all elements in the list to find if its ready to be
deleted (killed) has O(n) time , and remove operation takes O(n).
This leaves us to use HashMap<String,Creature> ( O(1) insert, O(1) search, O(1) delete).
(i think hashMap is called unordered_map in c++).
So every unit will have a unique name/id, so we will know what to delete. We will keep a list
"list_that_must_be_deleted" that shows which things must be deleted (in order to delete
later), with the following command (pseudocode):
for(Creature c in list_that_must_be_deleted )
{
HashMap.remove(c.getName());
}
Questions :
1) Are there any other design patterns , that have same or better speed than 2nd design ?
2) Do you think the 2nd design its an okay/correct design pattern ?
thanks,
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|