c++ - 如果存在虚函数,则无法通过地址减法/加法到达成员变量的地址
问题描述
我们正在与一个团队一起开发一个引擎,一个特定的功能将要求我们通过向类的地址添加值来访问每个成员的内存地址。这对于组件保存-加载系统是必需的,其中组件的每个成员都将被保存,然后如果用户加载场景则重新加载。显然,由于用户也可以创建组件,我们不能只是继续手动设置每个成员的值——因为用户创建的那些我们并不知道。在写这篇文章时,我发现虚拟功能被中断了——最初我不知道为什么我们无法联系到成员。
在以下场景中,我想访问 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之后的一个字节,正如预期的那样
有没有人知道如何忽略/跳过虚拟并能够根据其地址操纵成员值?
解决方案
推荐阅读
- mysql - 如何通过'ip'在mysql中透视表
- python - 将大字节对象转换为整数列表的更快方法
- c++ - Tensorflow 冻结图在 C++ API 中产生空输出
- django - Django-taggit,标签蛞蝓没有链接到正确的 ListView
- laravel - 图像上传和类 App\Image 在共享服务器中托管的 Laravel 项目中不起作用
- go - 如何两次解锁互斥锁
- azure - 在 Powershell 中修改逻辑应用连接
- ios - Flutter build iOS 卡在 Building [bundle id] for device (iOS-release)
- bash - 使用小写字母、大写字母和数字排序列表
- r - 单层感知器收敛