从指向某个成员的指针获取指向对象的指针 [英] Get pointer to object from pointer to some member

查看:125
本文介绍了从指向某个成员的指针获取指向对象的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个结构

struct Thing {
  int a;
  bool b;
};

我得到一个指向成员的指针 b 的结构,作为一些函数的参数:

and I get a pointer to member b of that structure, say as parameter of some function:

void some_function (bool * ptr) {
  Thing * thing = /* ?? */;
}

如何获取指向包含对象的指针? strong>最重要的是:在不违反标准中的某些规则的情况下,我想要标准定义的行为,而不是未定义的行为,也不是实现定义的行为。

How do I get a pointer to the containing object? Most importantly: Without violating some rule in the standard, that is I want standard defined behaviour, not undefined nor implementation defined behaviour.

推荐答案

如果你确定指针真的指向成员 b 在结构中,就像有人做了

If you are sure that the pointer is really pointing to the member b in the structure, like if someone did

Thing t;
some_function(&t.b);

那么你应该能够使用 offsetof 宏,以获取结构的指针:

Then you should be able to use the offsetof macro to get a pointer to the structure:

std::size_t offset = offsetof(Thing, b);
Thing* thing = reinterpret_cast<Thing*>(reinterpret_cast<int8_t*>(ptr) - offset);


$ b < t实际上指向 Thing :: b 成员,那么如果使用指针 thing 。

Note that if the pointer ptr doesn't actually point to the Thing::b member, then the above code will lead to undefined behavior if you use the pointer thing.

这篇关于从指向某个成员的指针获取指向对象的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆