问题
I've got a game server. It creates number of instances of Game
and adds them (Or a pointer to them? What's better? It has 10 ints
and 5 other pointers, 10 member functions) to the vector. After that some events happen inside of the game e. g. game_ends. At this very moment the game should be deleted from the vector... What is the best way to achieve it?
The two ways we've come to are:
create an observer pattern. server will be an observer and game will dispatch an event to delete it.
set the game to
ended
state while server constantly scans the vector and deletes that games which are inended
state.
回答1:
Pointers or instances
If you create a pointer using new
you have to remember to delete it. If you are using a real instance, make sure you define a copy constructor
, because std::vector
copies your objects often.
You can use boost::sharedPointer<Game>
. Do not use std::auto_ptr<Game>
with std::vector
From the implementation options I would consider the following :
The observer pattern is elegant, but how many times will it be called? Deletion from the vector will be O(n) because you will have to find it and then erase
it.
If you know the maximum games you will have in, say a minute, and that fits into memory, you can just have a thread which iterates through the vector every minute and deletes any ended
games.
If memory is critical, you have to use the observer pattern. If you have lots of games, and an unique identifier for each game, you can consider std::map
instead of vector
, and then use the observer pattern to delete from the map which will be O(log(n))
回答2:
The nature of your application aside, if you add objects to your vector by value rather than pointer, once they are deleted from the vector, you will not have to worry about deleting them yourself. If you have to create the objects dynamically and add them to your vector as pointers you will be responsible for their deletion.
回答3:
An object shouldn't really determine its own lifetime. You should probably have some sort of managing context which owns the container and which can decide when an object needs to go. The actual Game
elements may somehow notify the manager that they're done, but they shouldn't delete themselves, or remove themselves from a collection.
回答4:
Create an object or a pointer to object game?
Is the game object large? Does it contain other pointers or pointers to files, sockets or other such things?
If the answer to either of those is yes, then you should new the game object, and store a pointer to it.
Should you use observer or constantly scan?
To answer this better I would need to know more about your program. Currently it seems like a design decision you are better fit to make. If you scan constantly you will need to spin a thread. This might not be what you want.
I personally would use an observer pattern.
来源:https://stackoverflow.com/questions/12100816/c-managing-objects