【发布时间】:2014-09-19 20:59:49
【问题描述】:
还有另一个 enable_shared_from_this 问题:基本上,我得到了三件事。
- 系统类包含应用程序逻辑,可能是也可能不是事件监听器。
- 某种 EventManager,将事件映射到感兴趣系统的 shared_ptrs。
- 某种 SystemManager,它持有一个 std::list 的 shared_ptrs 到 System 对象。
现在,每个系统都应该能够向 EventManager 注册它感兴趣的各种事件。此外,如果它们不再对这些事件感兴趣,它们应该能够注销自己的这些事件.
但是,我不确定如何在系统管理器中创建系统并以避免两个所有权组的方式进行注册。
来自 SystemManager:
void SystemManager::AddSystem(GameSystem* system)
{
// Take ownership of the specified system.
systems.push_back(std::shared_ptr<GameSystem>(system));
}
来自事件管理器:
typedef std::shared_ptr<IEventListener> EventListenerPtr;
void EventManager::AddListener(EventListenerPtr const & listener, HashedString const & eventType)
{
// Get the event type entry in the listeners map.
std::map<unsigned long, std::list<EventListenerPtr>>::iterator iterator = this->listeners.find(eventType.getHash());
if (iterator != this->listeners.end())
{
std::list<EventListenerPtr> & eventListeners = iterator->second;
// Add listener.
eventListeners.push_back(listener);
}
else
{
// Add new entry to listeners map, removed for sake of simplicity of this example.
}
}
来自某个想要接收事件的任意系统:
void RenderSystem::InitSystem(std::shared_ptr<GameInfrastructure> game)
{
// BAD: Creates second ownership group.
this->game->eventManager->AddListener(std::shared_ptr<IEventListener>(this), AppWindowChangedEvent::AppWindowChangedEventType);
}
我已阅读推荐 enable_shared_from_this 的参考资料。但是,由于系统不拥有自己,因此它们无权访问最初创建系统并取得系统所有权的 SystemManager 持有的 shared_ptr。
有什么优雅的方法可以解决这个问题吗?
【问题讨论】:
-
这就是
enable_shared_from_this的用例,它使您可以访问拥有您的shared_ptr。
标签: c++ c++11 boost shared-ptr smart-pointers