我有一个包含一些数据成员的自定义类。我有一个指向类的数据成员之一的指针,我想有一个指向它的封闭实例的指针。例如:
class MyClass{
public:
int a;
int b;
virtual ~MyClass(){//because MyClass is not POD type
}
};
...
int* aptr = ...; //something valid, and i know its a pointer to a MyClass::a member
MyClass* classptr = ?; //how can i get a pointer to the class instance?
该类不是 POD 类型,因此 offsetof 宏并不总是有效/它会给出编译警告。
是否可以获得指向 MyClass 实例的指针?
最佳答案
您不能使用定义明确的 C++ 执行此操作,因为在不相关的类型之间进行强制转换是未定义的行为。
实际上,您可能会假设类的第一个成员的地址与类的地址相同,但偏移了系统上指针的大小。 (这个指针是你的 v 表的实现,它在 C++ 实现中是相当一致的。)然后,如果你对数据成员的打包做出一些假设,那么你对你的指针进行手动调整以从一个数据成员移动到其他。 offsetof
是另一种技术,在这里可以为您提供帮助,但它在您的上下文中仍然没有明确定义。
要么用特定的编译器断言乱扔你的源代码(因为你限制了可移植性),要么采用不同的技术。我当然会采用后者。
这里有一些非常糟糕的代码,向您展示了如何去做。考虑
struct Foo
{
virtual ~Foo(){}; /*introduce a v-table*/
int n;
};
还有,
Foo foo;
foo.n = 0xdeadbeef; // To test
int* p = &foo.n; // Suppose this is our pointer.
char* pp = (char*)(void*)p; // This cast is undefined behaviour.
pp -= 8; // Skip over 64 bit v-table. More undefined behaviour.
Foo* ph = (Foo*)(pp); // Yet more undefined behaviour.
ph
指向一个 Foo
实例。
关于c++ - 从成员指针获取指向封闭实例的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31961325/