将指向未知实例(但已知 class)的已知成员的指针转换为拥有实例

Convert a pointer that points to a known member of an unknown instance (but known class) to the owning instance

给定一个指向对象已知成员的指针,我如何才能获得指向封闭对象的指针?

有没有比下面更好的方法?它甚至有效吗?

struct data {
    int a,b;
};

data dummy;
static const std::ptrdiff_t offs_a = reinterpret_cast<char*>(dummy.a) - reinterpret_cast<char*>(dummy);
void main(){
    data d;
    int *v = &(d.a);
    data *owner = reinterpret_cast<data *>(reinterpret_cast<char*>(v) - offs_a);
    owner->b = 1;
}

特别是,我不喜欢使用虚拟对象 dummy 来确定指针偏移量。 有没有一种方法可以使用指向成员的指针来直接强制转换以指定 v 指向哪个(已知)成员?

您可以使用 offsetof 宏。

引用 cppreference:

The macro offsetof expands to an integral constant expression of type std::size_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified member, including padding if any.

它只保证对 standard layout types 有效,但对于您的情况应该没问题。

编辑:原始代码可以这样写:

data d;
int *v = &(d.a);
data *owner = reinterpret_cast<data *>(reinterpret_cast<char *>(v) - offsetof(data, a));
owner->b = 1;