从基类指针到派生类指针的static_cast无效

static_cast from base class pointer to derived class pointer is invalid

本文关键字:指针 static cast 无效 基类 派生      更新时间:2023-10-16

我正在创建一个简单的测试实体组件系统。我有一个基Component类,其中包含多个派生类。然后,我有几个系统将这些组件应用了一些逻辑。

// Component.h
// ------------
class Component
{
public:
    Component();
    ~Component();
}

// ControlComponent.h
// -------------------
#include <string>
#include "Component.h"
class ControlComponent : public Component
{
public:
    std::string input = ""; // store simple input instruction
    ControlComponent();
    ~ControlComponent();
};

// ControlSystem.cpp
void ControlSystem::update(Entity* entity)
{
    vector<Component*>* components = entity->getComponents();
    for (Component* component : *components)
    {
        PositionComponent* pc = static_cast<PositionComponent*>(component);
        ControlComponent* cc = static_cast<ControlComponent*>(component);
        if (pc != nullptr && cc != nullptr)
        {
            std::cout << "Which direction would you like to go?" << std::endl;
            std::string input;
            std::cin >> input;
            cc->input = input; // application breaks here
            // Apply some logic...
        }
    }
}

当我从基Component* static_cast到派生组件中的任何一个(PositionComponent*ControlComponent*)并且当两个结果都不nullptr时(即强制转换成功),我得到无效值,例如cc->input无法从字符串中读取字符等。

我在实体工厂中连接组件,如下所示:

void EntityFactory::wireUpPlayer(Entity* player)
{
    player->addComponent(new HealthComponent());
    player->addComponent(new ControlComponent());
    player->addComponent(new PositionComponent());
}

addComponent 的实现如下:

void Entity::addComponent(Component* component)
{
    m_components.push_back(component);
}

这些组件显示具有有效的内存地址,因此我不确定问题来自何处。

static_cast

运行时不检查有效性;如果转换已编译,则在运行时假定转换正常。如果不强制转换空指针,则static_cast的结果将不是空指针。要获得选中的转换,您需要dynamic_cast,这反过来又需要将指针转换为指向多态类型,即至少具有一个虚函数的类型。这意味着更改Component以至少有一个虚拟功能。

当我从基础Component* static_cast到派生组件中的任何一个(PositionComponent*ControlComponent*)并且两个结果都不nullptr时(即转换成功)......

当从基类强制转换为派生类时,static_cast告诉编译器,"相信我,我知道我在做什么。换句话说,如果它甚至可能是合法的,它将"成功"并返回非nullptr。 如果在运行时不合法,您将获得未定义的行为,因为尝试使用一个类的实例,就好像它是另一个类一样。

请改用dynamic_cast

正如 Pete Becker 和 Josh Kelley 所说,使用 dynamic_cast,我相信您还需要将至少一个函数设置为 virtual 。如果不这样做,编译器将不会记录继承,dynamic_cast可能仍会返回nullptr 。执行继承时,我建议将类析构函数设置为虚拟。当需要在派生类的析构函数中释放非托管资源并且您只有一个指向基类的指针时,这也是一种很好的做法,只要析构函数是虚拟的,才会调用派生类析构函数。有一篇文章在这里解释了它:什么时候使用虚拟析构函数?