给定一个指向对象已知成员的指针,我如何才能获得指向封闭对象的指针?
还有比下面的更好的方法吗?它甚至有效吗?
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 typestd::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;
关于c++ - 将指向未知实例(但已知类)的已知成员的指针转换为拥有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58030487/