c++ - 向我的地图添加 shared_ptr 会引发读取访问冲突
问题描述
所以我正在用 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
解决方案
推荐阅读
- deep-learning - 谁能解释一下 Feature Pyramid Networks for Object Detection 论文中的“非滑动窗口”声明?
- html - HTML 表单选择:选项属性 selected="selected" 和 default="default" 不起作用
- c++ - C ++:返回基于范围的具有继承对象的for循环迭代器
- python - 如何优化这个创建字典列表的 for 循环?
- c++ - 是否有 UWP 不受支持的 API 列表?
- codenameone - 代号未将构建发送到服务器
- reactjs - create-react-app + typescript 不使用 browserslist
- javascript - 获取新数据后刷新Leaflet Js并将其添加到标记中
- matplotlib - 将 plt.contour 转换为 np.array(等高线图形值转换为 np.array)
- r - R. 使用调查、样条和仅一个自变量值的错误预测