无法修改从向量<shared_ptr static_pointer_cast派生<Base>>
Cannot modify Derived that was static_pointer_cast from a vector<shared_ptr<Base>>
标题描述了这种情况,但潜在的问题可能是完全不同的东西。
我正在尝试制作一个简单的 ECS 游戏引擎。我有一堆实体,每个实体都包含一个vector<shared_ptr<Component>>
.Component
是所有派生组件的基类。
在游戏循环中,我有不同的System
来更新具有某些组件的实体。我获得系统正确组件的方式是使用以下函数
template <typename T>
inline T& GetComponent(std::uint32_t type)
{
std::shared_ptr<Component> baseComponent = this->components[this->typeToIndexMap[type]];
std::shared_ptr<T> component = std::static_pointer_cast<T>(baseComponent);
return *(component.get());
}
问题是当我尝试修改系统中的组件(inputComponent.lastX = 5.f;
)时,它不起作用。下一帧的值相同。我猜发生了某种截止,因为我正在存储Component
但不确定如何解决这个问题。如果真的是这种情况,我该如何解决它的任何想法?
编辑 : 附加信息
实体在vector<shared_ptr<Component>>
中保存组件
添加组件
void Entity::AddComponent(std::shared_ptr<Component> component)
{
this->components.push_back(component);
this->componentBitset = this->componentBitset | component->GetComponentType();
this->typeToIndexMap[component->GetComponentType()] = this->components.size() - 1;
}
组件创建
std::shared_ptr<InputComponent> inputComponent = std::make_shared<InputComponent>(InputComponent());
entity->AddComponent(inputComponent);
组件结构
class Component
{
public:
// Constructor / Destructor
Component(std::uint32_t type);
~Component();
std::uint32_t GetComponentType();
private:
std::uint32_t type;
};
输入组件
class InputComponent : public Component
{
public:
InputComponent();
~InputComponent();
double lastX;
double lastY;
};
最后我们有系统
void InputSystem::Update(GLFWwindow* window, std::vector<std::shared_ptr<Entity>>& entities)
{
for (int i = 0; i < entities.size(); i++)
{
if (entities[i]->IsEligibleForSystem(this->primaryBitset))
{
InputComponent component = entities[i]->GetComponent<InputComponent>(ComponentType::Input);
double x, y;
glfwGetCursorPos(window, &x, &y);
// some other things are happening here
component.lastX = x;
component.lastY = y;
}
}
}
问题就在这里:
InputComponent component = entities[i]->GetComponent<InputComponent>(ComponentType::Input);
您实际上按值获取InputComponent
。尝试更改GetComponent
以便它将返回T*
,我在这里提到的第一行更改为:
InputComponent *component = entities[i]->GetComponent<InputComponent>(ComponentType::Input);
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中