C ++管理对象 [英] C++ managing objects

查看:92
本文介绍了C ++管理对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏服务器。它创建了 Game 的实例数量,并添加它们(或者指向它们的指针)?它有10 ints 和5个其他指针,10个成员函数)到向量。之后,一些事件发生在游戏e内。 G。 game_ends。在这个时刻游戏应该从向量中删除...什么是最好的方法来实现它?

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?

我们的两种方法是: / p>

The two ways we've come to are:


  1. 创建观察者模式。

  1. create an observer pattern. server will be an observer and game will dispatch an event to delete it.

将游戏设置为已结束状态,而服务器不断地扫描向量并删除结束 c>状态的游戏。

set the game to ended state while server constantly scans the vector and deletes that games which are in ended state.


推荐答案

指针或实例

code> new ,你必须记住删除它。如果您使用的是实例,请确保您定义了一个复制构造函数,因为 std :: vector

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.

您可以使用 boost :: sharedPointer< Game> 。不要使用 std :: auto_ptr< Game> std :: vector

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 :

观察者模式是优雅的,叫做?从向量中删除将是O(n),因为你必须找到它,然后 erase 它。

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.

如果内存很关键,你必须使用观察者模式。如果您有很多游戏和每个游戏的唯一标识符,您可以考虑 std :: map ,而不是向量,然后使用观察者模式从映射中删除 O(log(n))

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))

这篇关于C ++管理对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆