微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果存在虚函数,则无法通过地址减法/加法到达成员变量的地址

如何解决如果存在虚函数,则无法通过地址减法/加法到达成员变量的地址

我们正在与一个团队一起开发一个引擎,一个特定的功能需要我们通过向类的地址添加值来访问每个成员的内存地址。这是组件保存加载系统所需要的,其中组件的每个成员都将被保存,然后在用户加载场景时加载回来。显然,由于用户也可以创建组件,我们不能继续坚持手动设置每个成员的值——因为用户创建的值我们并不知道。在写这篇文章的时候,我发现虚函数中断了——最初我不知道为什么我们无法联系到成员。
在以下场景中,我想访问 Component 类的 componentID 变量。

组件.h:

class Component
{
private:
    static int componentID_Count;

protected:
    virtual void Start() {};
    virtual void Tick() {};
    friend class Entity;

public:
    int componentID; // This is originally private,we set it to public in order to test the mentioned system
    Component();
    inline int GetID() { return componentID; }
};

在 main() 中:

    Component c = Component();
    std::cout << (&c + 1) << std::endl;
    std::cout << "component address: " << &c << "   offset size: " << offsetof(Component,componentID)
        << "    component address + offset: " << (&c + offsetof(Component,componentID)) 
        << "    component id address: " << &c.componentID << std::endl;

我看到很多论坛都推荐offsetof(),我的经验如下:

  • (&c + 1) 返回 &c
  • 后 2 个字节的地址
  • (&c + offsetof(Component,componentID))返回&c后10个字节的地址(据说偏移量是8)
  • &c.componentID&c 之后的一个字节,符合预期

有没有人知道如何忽略/跳过虚拟并能够根据他们的地址操纵成员值?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。