所以我正在用 C++ 构建一个游戏引擎,只是为了学习目的。我正在尝试遵循实体组件系统,当我将组件添加到我的实体时遇到问题。
在我的 Entity 类中,我想将该实体的所有组件保存在:std::map<type_index, std::shared_ptr<Component>> components;
当我添加一个组件时,我的 Entity 类的 .h 文件中有这个方法:
template<typename T, typename... TArgs>
std::shared_ptr<T> addComponent(TArgs&&... mArgs) {
std::shared_ptr<T> component(new T(std::forward<TArgs>(mArgs)...));
component->entity = this;
component->init();
// This is where the error is being thrown
components.emplace(type_index(typeid(*component)), component);
return component;
}
在同样的方法中,我也做了一些不同的事情,比如尝试添加组件components[std::type_index(typeid(*component))] = component;
而不是使用 emplace,然后我也尝试std::move
将组件放入地图中。
我的确切错误是:
Unhandled exception thrown: read access violation.
**std::forward<std::_Tree_node<std::pair<std::type_index const ,std::shared_ptr<Component> >,void *> * &>**(...) returned 0x4. occurred