从成员指针获取类/结构对象

Met*_*hos 2 c++

我有C++结构

struct myStruct {
    int a;
    int b;
    int c;
}; 

myStruct b;
int *ptr = &b.c;
Run Code Online (Sandbox Code Playgroud)

如何从ptr中恢复myStruct对象?

(我知道我可以使用像C中的container_Of()这样的指针算术来实现这一点.基本上就像

reinterpret_cast<myStruct*>(reinterpret_cast<char *>(ptr) - offsetof(myStruct, c));
Run Code Online (Sandbox Code Playgroud)

我问是否有任何推荐/优雅的方式?)

Dan*_*ker 5

肯定没有推荐的方法,因为在C++中绝对不推荐这样做.这是正确答案必须是"不要那样做!"的问题之一.

使用C++而不是C的全部原因是,您希望将类数据结构封装在类中,并在其上定义合理的操作,而不是让整个程序了解数据结构的内部布局.

也就是说,offsetof您描述的技术将适用于普通的旧数据对象,因为它们与C结构没有区别.