无法修改从向量<shared_ptr static_pointer_cast派生<Base>>

Cannot modify Derived that was static_pointer_cast from a vector<shared_ptr<Base>>

本文关键字:gt lt pointer cast Base 派生 static shared 修改 向量 ptr      更新时间:2023-10-16

标题描述了这种情况,但潜在的问题可能是完全不同的东西。

我正在尝试制作一个简单的 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);